Finding the Differentiation Condition between 2 list in python

python python-2.7 list

39 观看

4回复

1480 作者的声誉

I am a newbie in python and I was trying to figure out, how do I differentiate between 2 lists which are as shown below

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

And

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

The Problem is, that both the lists have '' element, and I want a solid Condition which satisfies that if a list has an item which is a string and not ''. It is also possible that list has 7 '' and just one item is a string.

作者: M.S.P 的来源 发布者: 2017 年 9 月 15 日

回应 4


0

1337 作者的声誉

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

You can use all for checking this.

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
作者: Unni 发布者: 2017 年 9 月 15 日

1

17118 作者的声誉

It seems you want to filter empty strings from a list:

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

The condition is if item. To clarify, '' is an empty string. During iteration, if the item is '', the condition is False and thus the item is excluded from the result. Otherwise, the condition is True and the result is added to the list. See also this post.

This behavior is because all objects in Python have "truthiness" - all objects are assumed True except for a few, such as False, 0, "", None and empty collections.

作者: pylang 发布者: 2017 年 9 月 15 日

2

43811 作者的声誉

决定

You can just use any with the list as argument :

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

If there's any element which is truthy (i.e. non empty), it will return True.

作者: Eric Duminil 发布者: 2017 年 9 月 15 日

0

30969 作者的声誉

The easiest way to see if there is not a '' in your list is to use not in:

tests = [
    ['11-10-2017', '12:15 PM', 'B.ARTS', 'Linguistics', '', '', 'German', 'Name'], 
    ['', '', '', '', '', '', '', ''], 
    ['a', 'b', 'c'],
    ['', '', '', '', '', 'x', '', '']]

for t in tests:
    print '' not in t, t

Which would display:

False ['11-10-2017', '12:15 PM', 'B.ARTS', 'Linguistics', '', '', 'German', 'Name']
False ['', '', '', '', '', '', '', '']
True ['a', 'b', 'c']
False ['', '', '', '', '', 'x', '', '']
作者: Martin Evans 发布者: 2017 年 9 月 15 日
32x32