简体   繁体   English

在不使用 insert() 的情况下将项目插入 Python 列表

[英]Insert an item to a Python list without using insert()

How do you add an item to a specific position on a list.如何将项目添加到列表中的特定 position。 When you have an empty list and want to add 'z' to the 3rd position using insert() only insert it at the last position like,当您有一个空列表并想使用 insert() 将“z”添加到第三个 position 时,只需将其插入到最后一个 position 中,例如,

l.insert(3,'z')
l
['z']

I want the output to be我希望 output 成为

[None, None, None, 'z']

or或者

['','','','z']

Assuming you want to have it in the Nth index:假设您想将它放在第 N 个索引中:

l = l[:N] + ['z'] + l[N:]

If you start with an empty list and want it to have Nones at the start and end of array, maybe this will help you (N is the number of None items you want):如果您从一个空列表开始并希望它在数组的开头和结尾有 Nones,也许这会对您有所帮助(N 是您想要的 None 项目的数量):

l = [None] * N
l = l[:N] + ['z'] + l[N:]

Try this method using a list comprehension -使用列表理解尝试此方法 -

n = 5
s = 'z'

out = [None if i!=n-1 else s for i in range(n)]
print(out)
[None, None, None, None, 'z']

If you want to insert the string somewhere in the middle, then a more general way is to define m and n separately where n is length of the list and m is the position -如果要在中间某处插入字符串,则更通用的方法是分别定义 m 和 n ,其中 n 是列表的长度, m 是 position -

n = 5
m = 3
s = 'z'

out = [None if i!=m-1 else s for i in range(n)]
print(out)
[None, None, 'z', None, None]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM