在Python中向列表插入元素

huangapple go评论60阅读模式
英文:

Inserting elements to a list in Python

问题

我有一个名为Cb的列表。我想在len(Cb[0])处插入元素0,但是我得到了一个错误。我展示期望的输出。

错误是

in <module>
    Cb=Cb[0].insert(0,len(Cb[0]))

TypeError: 'NoneType' object is not subscriptable

期望的输出是

[[1.0, 0.0, 0.0, 0.0]]
英文:

I have a list Cb. I want to insert element 0 at len(Cb[0]) but I am getting an error. I present the expected output.

Cb=[[1.0, 0.0, 0.0]] 

for i in range(0,len(Cb[0])):
    Cb=Cb[0].insert(0,len(Cb[0])) 
print(Cb)

The error is

in &lt;module&gt;
    Cb=Cb[0].insert(0,len(Cb[0]))

TypeError: &#39;NoneType&#39; object is not subscriptable

The expected output is

[[1.0, 0.0, 0.0, 0.0]]

答案1

得分: 1

在内部列表中简单地追加,使用 Cb[0].append(0)

英文:

Simply append to the inner list using Cb[0].append(0)

答案2

得分: 1

list.insert() 返回 None,这就是为什么你会收到一个错误。尝试这个:

Cb = [[1.0, 0.0, 0.0]]

Cb[0].extend([0] * (len(Cb[0]) + 1 - len(Cb[0])))

print(Cb)

这里有一个更具动态性并返回预期输出的代码版本。

英文:

list.insert() returns None thats why you're getting an error try this :

Cb = [[1.0, 0.0, 0.0]]

Cb[0].extend([0] * (len(Cb[0]) + 1 - len(Cb[0])))

print(Cb)

Here's a version of code that is more dynamic and return the expected ouptup

答案3

得分: 1

Output is :
[[1.0, 0.0, 0.0, 0.0]]

英文:
cb=[[1.0, 0.0, 0.0]]
cb[0].append(0.0)
print(cb)

Output is :

[[1.0, 0.0, 0.0, 0.0]]

huangapple
  • 本文由 发表于 2023年3月7日 19:41:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定