[英]Compare multiple unique strings in a list
編輯:我使用的是Python 2.7
我有一個給定的'矩陣',如下所示,其中包含多個字符串列表。 我想通過矩陣排序,只打印出只包含一組特定字符串的行。
任何人都可以給我一個如何解決這個問題的提示嗎?
到目前為止我嘗試過的:
matrix = [("One", "Two", "Three"),
("Four", "Five", "Six"),
("Seven", "Eight", "One"),
("Four", "Five", "Six"),
("One", "Three", "Six")]
for index, data in enumerate(matrix):
if "One" and "Three" and "Six" in data:
print data
期望的輸出:
("One", "Three", "Six")
實際產出(截至目前):
('Four', 'Five', 'Six')
('Four', 'Five', 'Six')
('One', 'Three', 'Six')
您的測試不正確,您想要使用in
分別測試每個字符串:
if "One" in data and "Three" in data and "Six" in data:
and
不為組操作數in
測試; 每個組件分別進行評估:
("One") and ("Three") and ("Six" in data):
這導致返回"Six" in data
中"Six" in data
的結果; 其他兩個值肯定都是True,因為它們是非空字符串。
更好的方法是使用一組 :
if {"One", "Three", "Six"}.issubset(data):
我會用套裝:
matrix = [("One", "Two", "Three"),
("Four", "Five", "Six"),
("Seven", "Eight", "One"),
("Four", "Five", "Six"),
("One", "Three", "Six")]
target = {"One", "Three", "Six"}
for row in matrix:
if target <= set(row):
print row
這里, target <= set(row)
檢查target
是否是set(row)
的子集。
您的代碼不起作用的原因如下:
if "One" and "Three" and "Six" in data:
相當於:
if bool("One") and bool("Three") and ("Six" in data):
由於bool("One")
和bool("Three")
為True
,因此整個表達式只檢查"Six"
是否在data
。
這背后的原因是你誤用了and
嘗試
"One" and "Three"
在交互式控制台中 - 它會輸出True
,因為“One”和“Three”是“cast”tobooleans,並且它們被視為真正的值。 所以,為了這個工作,你應該重寫條件
if "One" in data and "Three" in data and "Six" in data
你為什么不把它作為一套測試:
for data in matrix:
if set(["Three","Six","One"]).issubset(set(data)):
print data
結果是:
('One', 'Three', 'Six').
請注意,當您作為集合進行測試時,排序存在問題。
實際上,用你的if
語句
if "One" and "Three" and "Six" in data:
你得到包含Six
所有列表,( 注意你的輸出 )
("Seven", "Eight", "One")
和("One", "Two", "Three")
沒有打印,因為Six
不在你的元組中:
另外,每個字符串(不是""
)如果在python中為true,例如:
>>> if("One"):
... print "Yes"
... else:
... print "No"
...
Yes
所以,如果表達你
if "One" and "Three" and "Six" in data:
相當於
if True and True and "Six" in data:
這相當於:
if "Six" in data:
你需要在哪里“One”,“Three”和“Six”都存在,所以這樣做:
if ( ("One" in data) and
("Three" in data) and
("Six" in data)
):
正如@Martijn Pieters回答的那樣。 另外還有一種技術:
>>> target = {"One", "Three", "Six"}
>>> for data in matrix:
... if (set(map(tuple, data)) <= set(map(tuple, target))):
... print data
...
('One', 'Three', 'Six')
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.