我正在尝试过滤以下列表:
tuple = [('7:29', 0.5), ('99:2', 0.35714285714285715), ('10:2', 0.35714285714285715)]
使用列表推导,基于第一个元素进行过滤来自字符':'之间的元组。
例如:filter = [7, 99]
,因此结果将是:new_tuple = [('7:29', 0.5), ('99:2', 0.35714285714285715)]
.
我尝试了以下解决方案:
filter_string = [str(item) for item in filter]
tuple_filtered = [(x,y) for (x,y) in tuples if x in filter]
但它返回一个空列表,我不知道如何修复它。 有人可以帮帮我吗?
最佳答案
首先应用此行时:
filter_string = [str(item) for item in filter]
您将 str() 函数应用于一个元组对象 - 将所有元组放入一个字符串。
例如 - str(('99:2', 0.35714285714285715))
--> '(\\'99:2\\', 0.35714285714285715)'
在我看来,这只会让解析变得更加困难。
第二,tuple
是python中保存的名称——不要使用它并运行它!
以后可能会导致非常烦人的错误。
最后,您可以将元组视为固定大小的索引数组,这意味着您可以寻址第一个元素(您要过滤的元素)
类似的东西:
my_tuples = [('7:29', 0.5), ('99:2', 0.35714285714285715), ('10:2', 0.35714285714285715)]
my_filter = [7, 99]
filtered_list = [t for t in my_tuples if int(t[0].split(':')[0])
in my_filter]
关于使用元组的 Python 列表理解过滤(包含整数作为字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61140516/