![](/img/trans.png)
[英]How to compare elements in lists and check if first list element contains in another list's element using python
[英]Python: compare first element of lists effectively
在Python中,我有一個名為“ list1”的列表,其中包含可變長度的列表。
如果要添加的第一個元素不是list1中任何列表的第一個元素,我想向該長列表添加第二個列表“ add”。
此代碼有效:
list1 = [["a", 5, 9, 22], ["b", 10, 1], ["c"], ["d", 42]]
add = ["e", 1, 31]
add2 = ["b", 1, 31]
temp = []
for e in list1:
temp.append(e[0])
if add[0] not in temp:
list1.append(add)
如預期的那樣,將add ist添加到list1而不會添加add2。
但是,我想知道是否有更優雅,更有效的方法來避免創建臨時列表。
您可以使用all()
和一個生成器表達式進行測試:
if any(add[0] != elem[0] for elem in list1):
list1.append(add)
all()
函數遍歷所包含的生成器表達式測試,其中僅包含True
值,但是如果遇到False
(其中add[0]
等於elem[0]
)則將停止。 這樣省去了遍歷所有 list1
來查找elem[0]
是否已經存在的elem[0]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.