如何将循环列表放置到另一个新列表中?

问题描述 投票:2回答:1

代码

#Variables
var1 = ['Warehouse Pencil 1.docx', 'Production Pen 20.docx']

list1 = []
for x in var1:
    splitted = x.split()
    a = [splitted[0] + ' ' + splitted[1]]
    list1.append(a)
    print(list1)

输出

[['Warehouse Pencil']]
[['Warehouse Pencil'], ['Production Pen']]

目标

我打算拆分列表,并在每个部分抓住第一和第二个单词。并将它们放入新列表。

问题

为什么我的输出给我一个奇怪的输出?我要去哪里错了?

所需的输出

我期望的输出应如下所示:

['Warehouse Pencil', 'Production Pen']

抓取第一个和第二个单词并将它们放入一个列表。

python
1个回答
1
投票

这应该解决它-将print语句移出循环,并使a为字符串而不是列表。

#Variables
var1 = ['Warehouse Pencil 1.docx', 'Production Pen 20.docx']

list1 = []
for x in var1:
    splitted = x.split()
    a = splitted[0] + ' ' + splitted[1]
    list1.append(a)
print(list1)

输出:

['Warehouse Pencil', 'Production Pen']

您还可以使用列表理解:

>>> [' '.join(x.split()[:2]) for x in var1]
['Warehouse Pencil', 'Production Pen']

0
投票

这里是替代版本:

var1 = [
    'Warehouse Pencil 1.docx',
    'Production Pen 20.docx'
]

list1 = []
for x in var1:
    list1.append(' '.join(x.split()[:2]))
print(list1)

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.