[英]Accessing first element of a tuple in a list of tuples, in a list - python
Im fairly new to python, and I have a list of two lists, with 5 tuples each, called 'cos':我对python相当陌生,我有一个包含两个列表的列表,每个列表有5个元组,称为“cos”:
cos = ([('B6409', 0.9997), ('S4193', 0.9996), ('C9826', 0.9995), ('J6706', 0.9994), ('Q0781', 0.9993)] , [('A5474', 0.9985), ('H1286', 0.9981), ('Y1178', 0.998), ('D2742', 0.9979), ('A7668', 0.9979)])
Id like to iterate over this list and match the first element of each tuple, ie: 'B6409' and 'S4193' with the keys of a dictionary called 'dist', ie: 'R7033' , 'B6409' etc...我想遍历这个列表并匹配每个元组的第一个元素,即:'B6409'和'S4193'与一个名为'dist'的字典的键,即:'R7033','B6409'等......
dist = { 'R7033': [93.9636, 32.6327, 33.092] , 'V3259': [84.8378, 27.3658, 29.1537] , 'B6409': [55.6789, 67.5673, 89.7856] }
So effectively an if statement saying 'if the first element of each tuple in each list(two of them) is equal to a key in the dictionary 'dict', perform a calculation to sum up the values of that key.如此有效的 if 语句说“如果每个列表(其中两个)中每个元组的第一个元素等于字典 'dict' 中的键,则执行计算以总结该键的值。 So for example since the first element of one of the tuples in the list 'cos' is 'B6409', and it IS one of they keys in dictionary 'dict', sum up the list of values of key 'B6409'.
因此,例如,由于列表“cos”中的一个元组的第一个元素是“B6409”,并且它是字典“dict”中的一个键,因此总结键“B6409”的值列表。
Im just getting confused on the indexing of elements within the list of list with tuples and so far i have done only know to use我只是对带有元组的列表列表中的元素的索引感到困惑,到目前为止我只知道使用
for i in dist.keys():
for j in cos....
if i == cos[?][?][?]:
sum1 = sum(dist[i])
how is a way i can do this iteration loop?我怎么能做这个迭代循环? thanks
谢谢
If I understood your intention correctly, then you could use a comprehension to generate a list of keys from cos
and then another comprehension to generate a dictionary whose values are the corresponding sums:如果我正确理解了您的意图,那么您可以使用推导式从
cos
生成一个键列表,然后使用另一个推导式生成一个字典,其值是相应的总和:
cos = ([('B6409', 0.9997), ('S4193', 0.9996), ('C9826', 0.9995), ('J6706', 0.9994), ('Q0781', 0.9993)] , [('A5474', 0.9985), ('H1286', 0.9981), ('Y1178', 0.998), ('D2742', 0.9979), ('A7668', 0.9979)])
dist = { 'R7033': [93.9636, 32.6327, 33.092] , 'V3259': [84.8378, 27.3658, 29.1537] , 'B6409': [55.6789, 67.5673, 89.7856] }
keys = [item[0][0] for item in cos]
key_to_sum_dict = {key: sum(dist[key]) for key in keys if key in dist}
Which gives {'B6409': 213.0318}
.这给出了
{'B6409': 213.0318}
。
A way to iterate over cos
would be:一种迭代
cos
的方法是:
for dist_key in dist.keys():
for cos_list in cos:
for cos_tuple in cos_list:
if dist_key == cos_tuple[0]:
sum1 = sum(dist[dist_key])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.