3 回答
TA贡献1806条经验 获得超5个赞
首先,用于sum展平您的列表。
>>> sum(alist, [])
['ZZ Ward\\Eric Bell', 'ZZ Ward', 'Sabine Kabongo\\Salif Keita\\Cat Stevens\\Trilok Gurtu\\Lindsey Buckingham', 'John Mellencamp\\Cat Stevens']
然后您可以将所有列表条目连接成一个具有相同分隔符的字符串:
>>> "\\".join(sum(alist, []))
'ZZ Ward\\Eric Bell\\ZZ Ward\\Sabine Kabongo\\Salif Keita\\Cat Stevens\\Trilok Gurtu\\Lindsey Buckingham\\John Mellencamp\\Cat Stevens'
之后,您可以使用定界符拆分它们:
>>> "\\".join(sum(alist, [])).split("\\")
['ZZ Ward', 'Eric Bell', 'ZZ Ward', 'Sabine Kabongo', 'Salif Keita', 'Cat Stevens', 'Trilok Gurtu', 'Lindsey Buckingham', 'John Mellencamp', 'Cat Stevens']
现在一旦你有了它,你就可以使用 set 构造函数删除重复项,如上一个答案中所建议的那样:
>>> set("\\".join(sum(alist, [])).split("\\"))
{'Trilok Gurtu', 'Sabine Kabongo', 'Lindsey Buckingham', 'Salif Keita', 'ZZ Ward', 'Eric Bell', 'Cat Stevens', 'John Mellencamp'}
所以你看到你想要的所有操作都可以在一行中完成!
newlist = set("\\".join(sum(alist, [])).split("\\"))
TA贡献1856条经验 获得超17个赞
您可以list comprehension尝试set:
>>> new_list = [l3 for l1 in alist for l2 in l1 for l3 in l2.split('\\')]
>>> new_list
['ZZ Ward', 'Eric Bell', 'ZZ Ward', 'Sabine Kabongo', 'Salif Keita', 'Cat Stevens', 'Trilok Gurtu', 'Lindsey Buckingham', 'John Mellencamp', 'Cat Stevens']
>>> list(set(new_list))
['ZZ Ward', 'Salif Keita', 'Eric Bell', 'Lindsey Buckingham', 'Trilok Gurtu', 'Sabine Kabongo', 'John Mellencamp', 'Cat Stevens']
# If maintaining order is necessary:
>>> sorted(set(new_list), key=new_list.index)
['ZZ Ward', 'Eric Bell', 'Sabine Kabongo', 'Salif Keita', 'Cat Stevens', 'Trilok Gurtu', 'Lindsey Buckingham', 'John Mellencamp']
FWIW 基本上set comprehension可以,如果不需要订单:
>>> {l3 for l1 in alist for l2 in l1 for l3 in l2.split('\\')}
{'Cat Stevens',
'Eric Bell',
'John Mellencamp',
'Lindsey Buckingham',
'Sabine Kabongo',
'Salif Keita',
'Trilok Gurtu',
'ZZ Ward'}
在传统版本中,这可以像这样完成:
new_list = []
for l1 in alist:
for l2 in l1:
for l3 in l2.split('\\'):
if l3 not in new_list:
new_list.append(l3)
print(new_list)
输出:
['ZZ Ward', 'Eric Bell', 'Sabine Kabongo', 'Salif Keita', 'Cat Stevens', 'Trilok Gurtu', 'Lindsey Buckingham', 'John Mellencamp']
TA贡献1818条经验 获得超3个赞
列表理解是执行此操作的最佳方法,但如果您继续沿着您开始的路径前进,我认为这将解决问题。
alist = ["ZZ Ward\\Eric Bell"],["ZZ Ward"],["Sabine Kabongo\\Salif Keita\\Cat Stevens\\Trilok Gurtu\\Lindsey Buckingham"], ["John Mellencamp\\Cat Stevens"]
alist = list(filter(None, alist))
alist.sort()
for list in alist:
for element in list:
for item in element.split("\\"):
print(type(item), item)
添加回答
举报