如何查找一个单词是否出现两次,一个数字是否在一个元组中出现一次

时间:2019-11-14 14:47:15

标签: python

data = ((45, 'foot'), (21, 'basket'), (10, 'hand'), (24, 'foot'), (21, 'hand'))

def unique_data_items(data): 
  input data is made of ((int, string), (int, string), ...) 
  unique_nums = () #initialising the tuple 
  unique_words = () 
  Add code to fill the tuples unique_nums and unique_words with  
  numbers and words that are unique
  returns the pair (tuple) of the numbers of unique numbers and   
  words

我该如何完成代码,以便它可以返回出现一次的单词和出现两次的数字,我已经尝试过,但是无法弄清楚该怎么做,谢谢

1 个答案:

答案 0 :(得分:0)

d = {}
for x,y in data:
    if y not in d:
        d[y] = x
    else:
        d[y] += x
unique = tuple(d.items())

我想您希望此代码的输出是:

(('foot', 69), ('basket', 21), ('hand', 31))