[英]list inside list python
我不是要在列表中獲取列表而是我只想添加零但不知道如何。 看代碼
def myconv(x,h):
q=[]
print(h)
for i in range(len_h):
q.append(h[len_h-1-i])
print(q)
q.insert(0,([0]*len_h)) #I want this to add just plain zeros to the array... not an array insdie an
#like it is doing here
q.insert(len(q)+1,(0]*len_h))
print(q)
print(myconv([6,7,8,9],[1,2,3,4,5,6,7,8,9,0]))
你想使用+
,例如[0, 0, 0] + [2, 1, 3] == [0, 0, 0, 2, 1, 3]
0,0,0,2,1,3 [0, 0, 0] + [2, 1, 3] == [0, 0, 0, 2, 1, 3]
,將數組連接到第一個數組。 否則,您需要一次插入(或追加)一個項目。
為了演示列表乘法如何工作:
>>> [0]*2
[0, 0]
>>> [0]*5
[0, 0, 0, 0, 0]
我更喜歡就地擴展操作。 只是不要分配它,因為像大多數Python就地方法一樣,它返回None。
>>> l2.extend([0]*5)
>>> l2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0]
你有兩種方法:
q = [0]*len_h + q
要么
q[0:0] = [0]*len_h
q.insert(0,([0]*len_h))
這會在列表中創建一個列表,因為[0]*len_h
會創建一個新列表。 然后將該數組插入q
。 相反,將每個元素插入q
而不創建新列表。
for i in range(len_h):
q.insert(0, 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.