[英]Comparing a tuple in a list with another tuple
我有一個元組列表。 我想選擇列表中的每個元組,並將其與我定義的另一個元組進行比較。
我使用的代碼如下;
list1 = [(3, 4), (4, 5), (5, 6)]
for item in list1:
if list1[item] == (4,5)
print ("OK")
但是它說列表索引必須是整數或切片。 如果我想將列表中的每個元組與另一個元組進行比較,應該如何編碼?
請幫我!
如果你只有一個元組來檢查你並不需要循環。 只是直接檢查if
tpl = (4,5) # Single user defined tuple
if tpl in list1:
print ("OK")
如果您有很多元組要檢查
tuplst = [(3,4), (1,2)] # List of tuples
list1 = [(3, 4), (4, 5), (5, 6)]
for tpl in tuplst:
if tpl in list1:
print ("OK")
代碼中的問題是,當您執行list1[item]
,您嘗試執行list1[(3, 4)]
,這不是對列表建立索引的正確方法,因此會出現IndexError
您可以只測試元組(以下示例中的(4, 5)
)是否在列表中:
if (4, 5) in list1:
print('OK')
不需要顯式循環。
如果您有多個元組要檢查,我建議您使用set
s:
cmp = set(((4, 5), (5, 6)))
if cmp < set(list1):
print('OK')
這將檢查兩個元組是否在原始列表中至少出現一次。
嘗試這個:
list1 = [(3, 4), (4, 5), (5, 6)]
for item in list1:
if item == (4,5):
print ("OK")
您可以通過以下方式實現。
list1 = [(3, 4), (4, 5), (5, 6)]
for item in range(len(list1)):
if list1[item] == (4,5):
print ("OK")
else:
continue
替代解決方案:
for i in list1:
if i==(4,5):
print("Ok")
else:
....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.