在列表中比较多个唯一字符串

3

编辑:我使用的是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')
5个回答

8

你的测试不正确,你需要使用 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的结果被返回;另外两个值肯定总是True,因为它们是非空字符串。

更好的方法是使用集合

if {"One", "Three", "Six"}.issubset(data):

2
我会使用集合来完成这个任务:
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中。


0
为什么不将其作为一个集合进行测试:
for data in matrix:
    if set(["Three","Six","One"]).issubset(set(data)):
        print data

结果为:

('One', 'Three', 'Six').

请注意,当您作为一组进行测试时,排序可能会出现问题。

0

实际上,使用你的if语句

 if "One" and "Three" and "Six" in data: 

你会得到包含Six的所有列表,(注意你的输出

("Seven", "Eight", "One")("One", "Two", "Three")不会被打印出来,因为它们的元组中没有Six

此外,每个字符串(不是"")在Python中都是真实的,例如:

>>> 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')
>>> 

0

产生这种情况的原因是您错误地使用了and

尝试

"One" and "Three"

在交互式控制台中,它将输出True,因为"One"和"Three"被'转换'为布尔值,并且它们被视为真值。因此,为了使其工作,您应该重写条件为:
if "One" in data and "Three" in data and "Six" in data

“'One' and 'Three'” 实际返回“'Three'”,因为“'One'”评估(它没有被转换为布尔值)为True,所以返回值是and的第二个操作数。 - poke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接