【问题标题】:search specific tuples in list and dictionaries在列表和字典中搜索特定元组
【发布时间】:2016-05-25 17:41:22
【问题描述】:

假设我有一个这样的列表

liste=[(0,1,45), (0,2,90), (0,3,60), (1,2,50), (1,3,20), (2,3,25)]

还有另一个这样的列表:number_list=(0,2)

所以现在,我想要一个字典(或列表),其中每个键都有我的 liste 元组列表,这些元组包含 number_list 中的数字

以我为例,我想要的是:

d= { '0' : [(0,1,45), (0,2,90), (0,3,60)], '1' : [(1,2,50), (2,3,25)] }

到目前为止,我已经写了这个:

d={}
for x in range(len(number_list)):
        d[format(x)]=[item for item in liste if number_list[x] in item]
print d

但它不起作用,我不明白为什么?!

谢谢

【问题讨论】:

  • 你的意思不是'2' : 而不是'1' : 吗?还是索引?
  • it won't work 在这里工作(虽然输出有点不同,因为2 也在(0, 2, 90) 中)
  • 似乎是对的,您需要更准确地描述“行不通”的含义 - 实际发生的情况与您预期发生的情况之间的区别。
  • 谢谢你们!事实上我写的东西是有效的,但是在我的测试文件中我混淆了几个名字,所以它没有工作——'

标签: python list dictionary


【解决方案1】:

您可以使用字典理解:

>>> liste=[(0,1,45), (0,2,90), (0,3,60), (1,2,50), (1,3,20), (2,3,25)]
>>> number_list=(0,2)
>>> d = {str(x):[item for item in liste if x in item] for x in number_list}
>>> d
{'0': [(0, 1, 45), (0, 2, 90), (0, 3, 60)], '2': [(0, 2, 90), (1, 2, 50), (2, 3, 25)]}

另外——请注意,字典中的键不必是字符串。您可以只使用数字本身作为键,这可能更自然。

【讨论】:

    猜你喜欢
    • 2023-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多