Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 元组列表中第一个字符串后面有多少个整数_Python_List_Tuples - Fatal编程技术网

Python 元组列表中第一个字符串后面有多少个整数

Python 元组列表中第一个字符串后面有多少个整数,python,list,tuples,Python,List,Tuples,因此,我正在学习使用python,但在使用元组列表时遇到了困难。我试图在每个元组的名称后计算每个元组中的整数数。 例如,(‘百吉饼’,4,3,2,1),(‘馅饼’,6,5,4,2),(‘蛋糕’,12,11,10,0)] 我的目标是能够保存每个元组的名称,然后计算它们后面的整数数。我需要整数的数量,因为我必须考虑多个想要得到奖励的人 我的最终目标大概是。蛋糕:12个馅饼:6个,如果我印的是价值最高的两份。如何跳过字符串?您可以使用字典: s= [('bagels',4,3,2,1), ('pies

因此,我正在学习使用python,但在使用元组列表时遇到了困难。我试图在每个元组的名称后计算每个元组中的整数数。 例如,(‘百吉饼’,4,3,2,1),(‘馅饼’,6,5,4,2),(‘蛋糕’,12,11,10,0)]

我的目标是能够保存每个元组的名称,然后计算它们后面的整数数。我需要整数的数量,因为我必须考虑多个想要得到奖励的人


我的最终目标大概是。蛋糕:12个馅饼:6个,如果我印的是价值最高的两份。如何跳过字符串?

您可以使用字典:

s= [('bagels',4,3,2,1), ('pies',6,5,4,2), ('cakes',12,11,10,0)]
data = {i[0]:i[1:] for i in s}
要查找最高值,请执行以下操作:

highest_val = 2
final_treats = sorted(data.items(), key=lambda x:max(x[-1]))[-highest_val:]
输出:

[('pies', (6, 5, 4, 2)), ('cakes', (12, 11, 10, 0))]
使用听写理解:

这相当于以下内容:

r = {} # declare a dict
for v in data:
    i = v[0]        # find the item name
    j = max(v[1:])  # find the max of all integers following the item

    r[i] = j     # add an entry into the dictionary
详细信息

  • dict理解是用python表示
    for
    循环的一种简洁方式

  • v[0]
    检索第0个元素,并为其分配密钥

  • `max(v[1:])查找项后面的整数的max
最后,如果您想显示结果
r
,您可以对其进行迭代:

for k, v in r.items():
    print('{}:{}'.format(k, v))

cakes:12
bagels:4
pies:6
请注意,字典不是按顺序排列的,因此您不可能按输入条目的顺序打印结果。在这种情况下,您可以考虑使用<代码>列表 >:

r = ['{}:{}'.format(v[0], max(v[1:])) for v in data]

print(r)
['bagels:4', 'pies:6', 'cakes:12']
印刷也以类似的方式进行。如果要从最高到最低打印值,请使用
reversed=True调用
sorted

for i in sorted(r, reverse=True):
    print(i)

cakes:12
pies:6
bagels:4

OP想要
len(i[1:])
,而不是
i[1:]
,请参见我的答案。我不清楚这是如何与每个单独的tuple@Darkhail你迭代每个元组,提取第0个元素,找到大小,然后重复。那么我如何迭代每个元组呢?@Darkhail请重新阅读我的答案。。。我修改了它以返回最大值。
for i in sorted(r, reverse=True):
    print(i)

cakes:12
pies:6
bagels:4