简体   繁体   中英

Finding the Differentiation Condition between 2 list in python

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.

You can just use any with the list as argument :

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

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM