I have the following list:
mylist=[('captain', 'nemo', {'count': 698}), ('ned', 'land', {'count': 374}), ('captain', 'said', {'count': 170}), ('captain', 'nautilus', {'count': 142}), ('conseil', 'said', {'count': 142}), ('conseil', 'ned', {'count': 130}), ('said', 'ned', {'count': 126}), ('one', 'captain', {'count': 112}), ('said', 'sir', {'count': 104}), ('captain', 'replied', {'count': 86}), ('abraham', 'lincoln', {'count': 84}), ('nemo', 'nautilus', {'count': 84}), ('sea', 'nautilus', {'count': 80}), ('said', 'nemo', {'count': 78}), ('captain', 'sir', {'count': 72}), ('conseil', 'land', {'count': 72}), ('one', 'nemo', {'count': 68}), ('captain', 'ned', {'count': 68}), ('captain', 'nemos', {'count': 68}), ('water', 'nautilus', {'count': 68})]
and I want a simple set of all the string elements from this list. How do i do this?
Use a comprehension:
s = set([v for t in mylist for v in t if isinstance(v, str)])
print(s)
# Output
{'land', 'abraham', 'water', 'sea', 'nautilus', 'captain', 'one', 'ned',
'sir', 'lincoln', 'said', 'nemos', 'nemo', 'replied', 'conseil'}
As suggested by @chepner, every tuple have type Tuple[str,str,dict]
, you can do:
s = set([v for t in mylist for v in t[:2])
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.