I am a newbie to python and I am struggling to find a better way for a problem.
I have a list like below:
[(1048, u'3', u'1', ), (1048, u'03', u'00','Deleted' ), (1048, u'4', u'0', 'Deleted')]
In each tuple, the last attributed could be 'deleted' or 'None'. I need to check if all tuples have 'deleted' at last place.
How to do that.
I tried to do list comprehension ( https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions )
object_with_specific_attribute = [dataObj for dataObj in data if "Deleted" in dataObj[3]]
but it does not seem to be working in case of null data.
Can anybody please help?
Thanks in advance.
all(len(tup) == 3 or tup[-1] in [None, "Deleted"] for tup in data)
从你的例子中可以推断出一些元组没有第四项,所以我添加了len
检查。
all(item[-1] == "Deleted" for item in items)
This should return True
if they all contain "Deleted"
Also all your tuples need to have at least 4 elements. If not, you will get an index error
EDIT: As it stands in the comments it is better to go with item[-1]
as you stated: "last element"
下面的线会起作用。
object_with_specific_attribute = [tup for tup in data if tup[-1] == 'Deleted']
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.