如何在Python中比较元组中的元素

2024-07-07 05:36:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,遇到了以下练习:

给定以下元组的元组,比较每个元组的第一个元素,计算苹果、香蕉、瓜和菠萝的总数:

myTupleofTuples = (("apple",1),("banana",1),("apple",2),("melon",1),("pineapple",2),("banana",2))
for i,j in myTupleofTuples:
  counter = 0
  for k in range(len(myTupleofTuples)):
    if i in myTupleofTuples[k][0]:
      counter = counter + myTupleofTuples[k][1]
      print(i+" is in "  +myTupleofTuples[k][0]+ " the counter of " +i+ " is " ,counter )

我习惯于使用java或c,并以某种方式开发了以前的解决方案,尽管我希望有一个更像python且优雅的解决方案来解决这个问题


Tags: in苹果元素appleforiscounter解决方案
3条回答

与您的版本相当的Python版本(使用f-strings和解包变量):

for fruit1, number1 in myTupleofTuples:
    counter = 0
    for fruit2, number2 in myTupleofTuples:
        if fruit1 in fruit2:
          counter += number2
          print(f"{fruit1} is in {fruit2} the counter of {fruit1} is {counter}")

我会用一个Counter来计数水果(相同的名称,因此在比较名称时使用==而不是in):

from collections import Counter
counter = Counter()
for name, value in myTupleofTuples:
    counter[name] += value

我最喜欢的计数模式之一是使用defaultdict。像这样:

from collections import defaultdict

myTupleofTuples = (("apple",1),("banana",1),("apple",2),("melon",1),("pineapple",2),("banana",2))
sums = defaultdict(int)
for fruit, count in myTupleofTuples:
    sums[fruit] += count
print(list(sums.items()))

当你解决这个问题时,字典很方便。下面的代码就是一个例子

count_dict = {} # creating an empty dictionary
for fruit,num in myTupleofTuples: # loops each tuple and separate each individual tuple into fruit and num variable
  count = count_dict.get(fruit, 0) # get value if fruit exist in dictionary else give 0
  count_dict[fruit] = num + count # add the count with number

如果要按现有方式打印它们,请执行以下操作:

for key,value in count_dict.items():
  print('{} is in {} and There are {} {}\n'.format(key, [x for x in range(len(myTupleofTuples)) if myTupleofTuples[x][0]==key] value, key)) 
  # just adding list comprehension for finding index, you can use function as well

输出:

apple is in [0, 2] and There are 3 apple
banana is in [1, 5] and There are 3 banana
melon is in [3] and There are 1 melon
pineapple is in [4] and There are 2 pineapple

相关问题 更多 >