在python中寻找两个链表之间的区别条件

2024-06-14 05:08:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我想弄清楚,如何区分如下所示的两个列表

['11-10-2017', '12:15 PM', 'B.ARTS', 'Linguistics', '', '', 'German', 'Name']

以及

['', '', '', '', '', '', '', '']

问题是,这两个列表都有''元素,我需要一个实条件来满足,如果一个列表有一个不是''的字符串项。也有可能列表有7'',只有一项是字符串


Tags: 字符串name元素列表条件区分germanlinguistics
3条回答

I need a condition which is satisfied if there are no '', in the string.

您可以使用all来检查这个

In [1]: s1 = ['11-10-2017', '12:15 PM', 'B.ARTS', 'Linguistics', '', '', 'German', 'Name']
In [2]: s2 = ['11-10-2017', '12:15 PM']

In [4]: all(x for x in s1)
Out[4]: False

In [5]: all(x for x in s2)
Out[5]: True

只需将^{}与列表一起用作参数:

>>> any(['', '', '', '', '', '', '', ''])
False
>>> any(['', '', '', '', '', '', '', 'Test', ''])
True

如果有任何元素是真的(即非空),它将返回True

似乎要从列表中筛选空字符串:

lst = ['11-10-2017', '12:15 PM', 'B.ARTS', 'Linguistics', '', '', 'German', 'Name']
[item for item in lst if item]
# ['11-10-2017', '12:15 PM', 'B.ARTS', 'Linguistics', 'German', 'Name']

I want a solid Condition which satisfies that if a list has an item which is a string and not ''

条件是if item。澄清一下,''是一个空字符串。在迭代过程中,如果item'',则条件是False,因此从结果中排除该项。否则,条件是True,结果被添加到列表中。另见this post

此行为是因为all objects in Python have "truthiness"-所有对象都假定为True,只有少数对象除外,例如False0""None和空集合

相关问题 更多 >