说我有两个带有两个初始元素的列表:
a = [Mango, Orange]
和
b = [Max - Trom - Tyre | Men, Peter - Min - Mike | Doug]
我想输出类似以下内容的几列:
Mango Max Trom Tyre
Orange Peter Min Mike
换句话说,我想先将列表转置为两列,然后执行以下操作:
用'-'将第二个列表分成几列
删除“ |”之后的所有文本在第二个列表中
我看到了这篇帖子Python: Write two lists into two column text file,但这只能使我能够转置列表,而不能将列表元素分成几列
答案 0 :(得分:0)
这可能会有所帮助。
演示:
a = ["Mango", "Orange"]
b = ["Max - Trom - Tyre | Men", "Peter - Min - Mike | Doug"]
for i, v in zip(a, b): #Iterate Both List
v = v.split("|")[0] #Split by "|" and access first element
print([i] + v.split(" - ")) #Form required output.
输出:
['Mango', 'Max', 'Trom', 'Tyre ']
['Orange', 'Peter', 'Min', 'Mike ']
答案 1 :(得分:0)
使用以下代码:
a = ['Mango' , 'Orange']
b = ['Max - Trom - Tyre | Men' , 'Peter - Min - Mike | Doug']
c=list()
d=list()
for i in range(len(a)):
d=[]
d.append(a[i])
b1=b[i].split("|")[0]
for k in b1.split("-"):
d.append(k)
c.append(d)
print(c)
答案 2 :(得分:0)
a = ["Mango", "Orange"]
b = ["Max - Trom - Tyre | Men", "Peter - Min - Mike | Doug"]
def combine_name(key, value):
return [key] + [name.strip() for name in value.split("|")[0].split('-')]
print list(map(combine_name, a, b))
>>>[['Mango', 'Max', 'Trom', 'Tyre'],
['Orange', 'Peter', 'Min', 'Mike']]