如何在 python 中提取列表列表中的元素并创建另一个列表。所以,我想从中得到:
all_list = [['1 2 3 4','2 3 4 5'],['2 4 4 5', '3 4 5 5' ]]
Run Code Online (Sandbox Code Playgroud)
像这样的新列表:
list_of_lists = [[('3','4'),('4','5')], [('4','5'),('5','5')]]
Run Code Online (Sandbox Code Playgroud)
以下是我所做的,但它不起作用。
for i in xrange(len(all_lists)):
newlist=[]
for l in all_lists[i]:
mylist = l.split()
score1 = float(mylist[2])
score2 = mylist[3]
temp_list = (score1, score2)
newlist.append(temp_list)
list_of_lists.append(newlist)
Run Code Online (Sandbox Code Playgroud)
请帮忙。提前谢谢了。
您可以使用嵌套列表理解。(这假设您想要每个字符串的最后两个“分数”):
[[tuple(l.split()[-2:]) for l in list] for list in all_list]
Run Code Online (Sandbox Code Playgroud)