Home > Mobile >  How to extract all string elements from a list with tuples
How to extract all string elements from a list with tuples

Time:01-05

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?

CodePudding user response:

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'}
  •  Tags:  
  • Related