要先附加的词

时间:2013-10-05 09:17:36

标签: python list

如何在(First)

打印my_list后首先附加my_list = ['Hey','Lol (First)','Dasd','Go (First)','Asd'] for x in my_list: print(x) 的字词

如果相反,没有(第一个)的单词将首先附加。

{{1}}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:4)

使用列表理解:

>>> my_list = ['Hey','Lol (First)','Dasd','Go (First)','Asd']
>>> [x for x in my_list if 'First' in x] + [x for x in my_list if 'First' not in x]
['Lol (First)', 'Go (First)', 'Hey', 'Dasd', 'Asd']
>>> [x for x in my_list if 'First' not in x] + [x for x in my_list if 'First' in x]
['Hey', 'Dasd', 'Asd', 'Lol (First)', 'Go (First)']

>>> for x in [x for x in my_list if 'First' in x] + [x for x in my_list if 'First' not in x]:
...     print(x)
...
Lol (First)
Go (First)
Hey
Dasd
Asd
>>> for x in [x for x in my_list if 'First' not in x] + [x for x in my_list if 'First' in x]:
...     print(x)
...
Hey
Dasd
Asd
Lol (First)
Go (First)