在Python中通过拆分另一个列表的索引来创建列表是可能的吗?

2024-05-14 22:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了下面的代码,但到目前为止还不起作用,它说我不能

names = ['John Johnson Doe', 'Jane Janis Doe']
firstnames = []

for name in names:
     firstnames.append(names[name].split(' ')[0])
print(firstnames)

我在这里遇到的错误是:

TypeError: list indices must be integers or slices, not str

Tags: 代码nameinfornames错误johnsplit
3条回答

您可以直接创建firstnames

names = ['John Johnson Doe', 'Jane Janis Doe']

然后

firstnames = [n.split(' ')[0] for n in names]

firstnames
['John', 'Jane']

The error I am getting here is TypeError: list indices must be integers or slices, not str

python解释器cleary抛出的TypeError异常表示您试图使用str对象作为列表中的索引。这意味着变量name是程序中的str。我想你是假设它是一个int

Python for语句按顺序迭代序列的成员,每次执行块(for循环下的代码)

循环变量name将在每次迭代中引用列表names中的一个对象。它不包含序列中对象的索引

我假设您想要列表中每个字符串的名字names。下面是你应该如何使用list comprehensions

print([n.split(' ')[0] for n in names])

但是,我也修改了您的代码。试试这个:

names = ['John Johnson Doe', 'Jane Janis Doe']
firstnames = []

for name in names:
     firstnames.append(name.split(' ')[0])
print(firstnames)

产出:

['John', 'Jane']

如果您仍然需要indexes,那么您可以查看enumerate,尝试以下方法:

names = ['John Johnson Doe', 'Jane Janis Doe']
firstnames = []

for ndx,name in enumerate(names):
     firstnames.append(names[ndx].split(' ')[0])
print(firstnames)

变量name包含列表names的内容,而不是索引。所以在第一次迭代name = 'John Johnson Doe'中,您试图使用它作为names的索引,也就是说,您正在做names['John Johnson Doe']

只需在name而不是names[name]上进行拆分,所有操作都将正常工作

相关问题 更多 >

    热门问题