我想在清单中命名一个值

时间:2019-04-21 11:49:05

标签: python

基本上,列表中有一些整数值。我想给每个值一个名称,该名称是列表中的一个字符串,以便它显示我取出的值的名称。

我已经尝试过将名称放在引号中,但这似乎可行

eliminate = [Couple1,Couple2,Couple3,Couple4,Couple5,Couple6]
length = len(eliminate)
FSmallest = eliminate[0]
SSmallest = eliminate[1]
print(eliminate)
gone = print(FSmallest," and ",SSmallest," have been eliminated!")

当我运行此代码时。它给了我每对夫妇的人数,并说出我淘汰了哪些人数。我想告诉我我淘汰了哪对夫妇。例如,“ Couple1:30和Couple2:20已被淘汰!”但是在删除时,不允许我添加文字和数字。

1 个答案:

答案 0 :(得分:2)

您有3个选项(至少)。

  • 课程
  • 字典
  • 命名元组

1-类实现:

#Define the Couple class
class Couple:
    name = ""
    value = 0

    # The Constructor
    def __init__(self, the_name, the_value):
        self.name = the_name
        self.value = the_value

    # In this method we handle the output , when object is being printed.
    def __str__(self):
        return self.name + " : " + str(self.value)

#Create some objects 
couple_1 = Couple('couple1', 30)
couple_2 = Couple('couple2', 20)
couple_3 = Couple('couple3', 10)
couple_4 = Couple('couple4', 40)
couple_5 = Couple('couple5', 35)

#Put them in a list
eliminate = [couple_1, couple_2, couple_3, couple_4, couple_5] 
length = len(eliminate)
FSmallest = eliminate[0]
SSmallest = eliminate[1]
print(FSmallest, ' and ', SSmallest, ' have been eliminated!')

现在您的输出将如下所示:

couple1 : 30 and couple2 : 20 have been eliminated!

2-字典实现列表:

eliminate = [
    {'name':'couple1', 'value':30},
    {'name':'couple2', 'value':20},
    {'name':'couple3', 'value':10},
    {'name':'couple4', 'value':40},
    {'name':'couple5', 'value':35},
]
length = len(eliminate)
FSmallest = eliminate[0]
SSmallest = eliminate[1]
print(FSmallest['name'], ' : ', FSmallest['value'], ' and ',\
        SSmallest['name'], ' : ', SSmallest['value'], ' have been eliminated!')

结果相同。


3-命名为Tuples的实现:

namedtuple是类和字典的组合。 我们必须从收藏模块导入它。

from  collections import namedtuple



# Define a new namedtuple with 2 fields , name and value
# There are several ways to declare fields.
# Couple = namedtuple('Couple', ['name', 'value'])
# Couple = namedtuple('Couple', "name, value")
# Couple = namedtuple('Couple', "name value")

Couple = namedtuple('Couple', 'name value')

# Create some instances of our tuple
# We can declare the values of fields in 2 way
# First way is :
couple_1 = Couple(name='couple1', value=30)

# And the second way :
couple_2 = Couple('couple2', 20)
couple_3 = Couple('couple3', 10)
couple_4 = Couple('couple4', 40)
couple_5 = Couple('couple5', 35)

eliminate = [couple_1, couple_2, couple_3, couple_4, couple_5] 
FSmallest = eliminate[0]
FSmallest = eliminate[1]
print(FSmallest.name, ' : ', FSmallest.value, ' and ',\
        SSmallest.name, ' : ', SSmallest.value, ' have been eliminated!')