将项目从列表传递到另一个列表中的空对象
passing items from list to an empty object in another list
我想将列表中的项目传递给商店中的空对象,即我想要:
store = [ [['a', 'b'], ['c', 'd']], [] ]
我得到了一个意外的结果:
lists = [['a', 'b'], ['c', 'd']]
store = [[], []]
counter = 0
for l in lists:
for s in store:
s.append(l)
这给了我:
store = [[['a', 'b'], ['c', 'd']], [['a', 'b'], ['c', 'd']]]
商店有两个空列表,您正在向这两个列表添加内容。如果你只想添加到第一个则
for l in lists:
store[0].append(l)
嵌套的 for 循环有点矫枉过正。您应该 extend
store
中的第一个子列表 lists
:
lists = [['a', 'b'], ['c', 'd']]
store = [[], []]
store[0].extend(lists)
# ^ indexing starts from 0
print(store)
# [[['a', 'b'], ['c', 'd']], []]
在 lists
上查看更多内容
这是一个很简单的人。
最好的方法是简单地将列表分配给 stores[0]。
stores[0]= lists
这就是您需要做的。
简单地这样做怎么样:
store = [lists, []]
# value of 'store' = [[['a', 'b'], ['c', 'd']], []]
根据您的问题,我认为所需的 O/P 是:
store = [ [['a', 'b'], ['c', 'd']], [] ]
来自输入列表:
lists = [['a', 'b'], ['c', 'd']]
如果
store = [ [['a', 'b'], ['c', 'd']], [] ]
确实是你想要的,那你就过分了。内部循环是不必要的,它将为 store
中的 each 项目执行代码。您在 store
中有两个空列表,因此在代码具有 运行 之后在 store
中创建了两个填充列表。只做第一个,你想要
for l in lists:
store[0].append(l)
阅读你的问题,虽然我不是 100% 肯定这就是你真正想要的,尤其是。考虑到您原本神秘的内部循环。
我读 "I want to pass items from lists to the empty object in store" 可能意味着您正试图从 lists
中的两个列表中取出项目并将它们放在 store
中的一个列表中。如果那是你想要的,像这样的东西就可以了:
for l in lists:
for i in l:
store[0].append(i)
这给你:
[['a', 'b', 'c', 'd'], []]
我想将列表中的项目传递给商店中的空对象,即我想要:
store = [ [['a', 'b'], ['c', 'd']], [] ]
我得到了一个意外的结果:
lists = [['a', 'b'], ['c', 'd']]
store = [[], []]
counter = 0
for l in lists:
for s in store:
s.append(l)
这给了我:
store = [[['a', 'b'], ['c', 'd']], [['a', 'b'], ['c', 'd']]]
商店有两个空列表,您正在向这两个列表添加内容。如果你只想添加到第一个则
for l in lists:
store[0].append(l)
嵌套的 for 循环有点矫枉过正。您应该 extend
store
中的第一个子列表 lists
:
lists = [['a', 'b'], ['c', 'd']]
store = [[], []]
store[0].extend(lists)
# ^ indexing starts from 0
print(store)
# [[['a', 'b'], ['c', 'd']], []]
在 lists
这是一个很简单的人。 最好的方法是简单地将列表分配给 stores[0]。
stores[0]= lists
这就是您需要做的。
简单地这样做怎么样:
store = [lists, []]
# value of 'store' = [[['a', 'b'], ['c', 'd']], []]
根据您的问题,我认为所需的 O/P 是:
store = [ [['a', 'b'], ['c', 'd']], [] ]
来自输入列表:
lists = [['a', 'b'], ['c', 'd']]
如果
store = [ [['a', 'b'], ['c', 'd']], [] ]
确实是你想要的,那你就过分了。内部循环是不必要的,它将为 store
中的 each 项目执行代码。您在 store
中有两个空列表,因此在代码具有 运行 之后在 store
中创建了两个填充列表。只做第一个,你想要
for l in lists:
store[0].append(l)
阅读你的问题,虽然我不是 100% 肯定这就是你真正想要的,尤其是。考虑到您原本神秘的内部循环。
我读 "I want to pass items from lists to the empty object in store" 可能意味着您正试图从 lists
中的两个列表中取出项目并将它们放在 store
中的一个列表中。如果那是你想要的,像这样的东西就可以了:
for l in lists:
for i in l:
store[0].append(i)
这给你:
[['a', 'b', 'c', 'd'], []]