简体   繁体   English

Python 使用元组进行列表理解过滤(包含整数作为字符串)

[英]Python list comprehension filtering with tuples (containing integers as strings)

I am trying to filter the following list: tuple = [('7:29', 0.5), ('99:2', 0.35714285714285715), ('10:2', 0.35714285714285715)] using list comprehension, filtering based on the first elements from the tuples between the character ':'.我正在尝试过滤以下列表: tuple = [('7:29', 0.5), ('99:2', 0.35714285714285715), ('10:2', 0.35714285714285715)]使用列表理解,过滤基于字符“:”之间的元组中的第一个元素。 For example: filter = [7, 99] , thus the result would be: new_tuple = [('7:29', 0.5), ('99:2', 0.35714285714285715)] .例如: filter = [7, 99] ,因此结果将是: new_tuple = [('7:29', 0.5), ('99:2', 0.35714285714285715)]

I tried the following solution:我尝试了以下解决方案:

filter_string = [str(item) for item in filter]
tuple_filtered = [(x,y) for (x,y) in tuples if x in filter]

but it returns an empty list and I don't have any idea how to fix it.但它返回一个空列表,我不知道如何修复它。 Can somebody please help me?有人能帮帮我吗?

First when you apply this line:首先,当您应用此行时:

filter_string = [str(item) for item in filter]

You apply str() function over a tuple object - making all the tuple in to a string.您在元组 object 上应用 str() function - 将所有元组放入字符串中。 for example - str(('99:2', 0.35714285714285715)) --> '(\\'99:2\\', 0.35714285714285715)' Which in my sense just make it harder to parse.例如 - str(('99:2', 0.35714285714285715)) --> '(\\'99:2\\', 0.35714285714285715)'在我看来,这只会让它更难解析。

Second, tuple is a saved name in python - do not use it and run it over .其次, tuple是 python 中保存的名称 -不要使用它并运行它 it can cause very annoying bugs later on.以后可能会导致非常烦人的错误。

Finally, you can look at a tuple as a fixed size array which is indexed, which mean you can address the first element (that you want to filter by)最后,您可以将元组视为固定大小的索引数组,这意味着您可以处理第一个元素(您想要过滤的元素)

Something like that:像这样的东西:

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]
[(x,y) for (x,y) in tuples if  str(x.split(":")[0]) in filter_string ]

Equivalently:等效地:

op = []
for (x,y) in tuples :
    if str(x.split(":")[0]) in filter_string:
        op.append((x,y))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM