[英]Finding an item in list of tuples according to more than one value in Python
[英]Python 2.7: Removing tuples from a list by value basis more than one condition
假設我有以下格式的列表:
[(99.0,0.14),(101.0,0.11),(104.0,4.5),(78.0,14.0)]
我想遍歷浮點值的列表,檢查元組的第一個索引中的值是否大於100,並且元組的第二個索引中的值是否大於10,並且以上任一條件為真隨后將元組從列表中完全刪除。
為了得到這樣的東西:
[(99.0,0.14)]
我從@StefanPochmann對這個問題的上一版本的回答中嘗試了此方法:
z = [t for t in z if t[0] <= 100 and t[1] <= 10]
但由於我正在處理列表的元組中的浮點值,因此它返回此錯誤:
TypeError: 'float' object is not iterable
進行此檢查的最佳方法是什么?
列表理解,保持良好的元組。
>>> tuples = [(99,78),(101,46),(104,69),(0,32)]
>>> [t for t in tuples if max(t) <= 100]
[(99, 78), (0, 32)]
它不是一個元組而是一個列表。
編輯:這是對原始問題的答案,而不是當前答案無效的答案。
根據上述解決方案:
lt = [(99,78),(101,46),(104,69),(0,32)]
# additional function which checks whether the tuple
# contains elements greater than 100
all_less100 = lambda y: not bool(list(filter(lambda x: x > 100, y)))
# filter tuples that contains elements greater than 100
lt_filtered = list(filter(all_less100, lt))
print(lt_filtered)
max和min調用不執行任何操作:您一次只使用一個值。 擺脫那些。
z = [t for t in z if t[0] <= 100 and t[1] <= 10]
lt = [(99,78),(101,46),(104,69),(0,32)]
lt = filter(lambda x: x[0] < 100,lt)
print(list(lt))
[(99, 78), (0, 32)]
or with list comprehension
lt = [ (x,y) for x,y in lt if x < 100]
print(lt)
[(99, 78), (0, 32)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.