我有兩個串列l1并l2包含類似的元素
l1 = ['a','b','c','d']
l2 = ['a is greater', 'f is greater', 'c is greater']
我想比較 l1 的元素并查找 l2 是否包含在它們的元素中。愿望輸出將是
f is greater
按照我試過的代碼,
for i in l2:
for j in l2:
if j not in l1:
print(i)
但我觀察到的輸出是
a is greater
a is greater
f is greater
f is greater
c is greater
c is greater
請幫助我了解我需要添加什么才能獲得適當的輸出。謝謝。
uj5u.com熱心網友回復:
用:
l1 = ['a','b','c','d']
l2 = ['a is greater', 'f is greater', 'c is greater']
# iterate over the elements of l2
for i in l2:
# check if the first letter of e is in l1
if i[0] not in l1:
print(i)
輸出
f is greater
您不需要在 的元素上迭代兩次,也不需要l2檢查值 ( i[0]) 是否在集合 ( l1) 中使用in。
更新
如果您想檢查不同的位置,只需更改 i 上的索引,例如,如果您想檢查最后一個位置,請執行以下操作:
l1 = ['a','b','c','d']
l2 = ['Greater is c', 'Greater is f', 'Greater is d']
# iterate over the elements of l2
for i in l2:
# check if the first letter of e is in l1
if i[-1] not in l1: # note the -1
print(i)
輸出
Greater is f
如果您想考慮句子中不存在所有單詞(由空格分隔)的位置l1,一種方法:
l1 = ['a', 'b', 'c', 'd']
l2 = ['Greater is c', 'Greater is f', 'f is greater', "Hello a cat"]
s1 = set(l1)
# iterate over the elements of l2
for i in l2:
# check if the first letter of e is in l1
if s1.isdisjoint(i.split()):
print(i)
輸出
Greater is f
f is greater
如果檢查字串包含,請執行以下操作:
l1 = ['Book Date:', 'Statement Number:', 'Opening Book Balance:', 'Closing Book Balance:', 'Number Of Debits:',
'Number of Credits:', 'Total Debits:', 'Total Credits:', 'Report Date:', 'Created by:', 'Modified by:', 'Printed by:']
l2 = ['<p>Book Date: 06-01-21 To 06-30-21</p>', '<p>Statement Number: 126 </p>', '<p>this value need to print</p>']
# iterate over the elements of l2
for i in l2:
# check if the first letter of e is in l1
if not any(j in i for j in l1):
print(i)
輸出
<p>this value need to print</p>
uj5u.com熱心網友回復:
干得好:
ref = ('a','b','c','d')
l2 = ['a is greater', 'f is greater', 'c is greater']
l3 = ['Greater is c', 'Greater is f', 'Greater is d']
l4 = ['...c...', '...f...', '...d...']
[item for item in l2 if not item.startswith(ref)] # 'f is greater'
[item for item in l3 if not item.endswith(ref)] # 'Greater is f'
[item for item in l4 if not any(letter in item for letter in ref)] # '...f...'
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/339885.html
標籤:Python 蟒蛇-3.x 列表 python-2.7 数组列表
上一篇:將資訊從AJAX傳遞到控制器類
