Python 有没有办法在字符串列表中打印选定的单词?
我很难找到一种方法来只打印字符串列表中的对象(汽车、雨伞、汽车、海滩、笔记本) 另外,是否有方法从字符串列表(汽车、雨伞、海滩、笔记本)打印独特元素Python 有没有办法在字符串列表中打印选定的单词?,python,python-3.x,Python,Python 3.x,我很难找到一种方法来只打印字符串列表中的对象(汽车、雨伞、汽车、海滩、笔记本) 另外,是否有方法从字符串列表(汽车、雨伞、海滩、笔记本)打印独特元素 使用拆分: elements = [ 'cars, 1010, 1420', 'umbrellas, 1700, 1820', 'cars, 4010, 1220', 'beaches, 1800, 1120', 'notebooks, 0610, 0420'] print([string.split(',')[0] for string in
使用
拆分:
elements = [
'cars, 1010, 1420',
'umbrellas, 1700, 1820',
'cars, 4010, 1220',
'beaches, 1800, 1120',
'notebooks, 0610, 0420']
print([string.split(',')[0] for string in elements])
# ['cars', 'umbrellas', 'cars', 'beaches', 'notebooks']
如果您想要唯一的名称,只需使用集合压缩而不是列表:
print({string.split(',')[0] for string in elements})
# {'cars', 'notebooks', 'umbrellas', 'beaches'}
或与:
使用拆分:
elements = [
'cars, 1010, 1420',
'umbrellas, 1700, 1820',
'cars, 4010, 1220',
'beaches, 1800, 1120',
'notebooks, 0610, 0420']
print([string.split(',')[0] for string in elements])
# ['cars', 'umbrellas', 'cars', 'beaches', 'notebooks']
如果您想要唯一的名称,只需使用集合压缩而不是列表:
print({string.split(',')[0] for string in elements})
# {'cars', 'notebooks', 'umbrellas', 'beaches'}
或与: