簡體   English   中英

Python 使用元組進行列表理解過濾(包含整數作為字符串)

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

我正在嘗試過濾以下列表: 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]

您在元組 object 上應用 str() function - 將所有元組放入字符串中。 例如 - 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]
[(x,y) for (x,y) in tuples if  str(x.split(":")[0]) in filter_string ]

等效地:

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