社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

unfrlatting list在python中返回意外错误

Katekarin • 6 年前 • 1291 次点击  

我已经阅读了所有关于stackoverflow上取消列表的文章,但是我找不到解决我问题的方法。

我有两个列表,我想从列表2向列表1中的每个元素添加一个元素。

l1 = [[1,2],[3,4]]
l2 = [5, 7]

我追求的结果是

[[1, 2, 5], [3, 4, 6]]

我试过这个密码

for i in range(len(l2)):
    l1[i].extend(l2[i])

print(l1)

但返回错误“typeerror:'int'对象不可iterable”

当l2的每个元素本身都是一个列表时,例如 l2 = [[5],[7]] 我的代码工作正常。为什么?当l2为这种格式时,如何调整代码以使其正常工作 l2 = [5, 7]

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38387
 
1291 次点击  
文章 [ 3 ]  |  最新文章 6 年前
arundeep chohan
Reply   •   1 楼
arundeep chohan    6 年前
l1 = [[1,2],[3,4]]
l2 = [5, 7]
for i in range(len(l2)):
l1[i].append(l2[i]);

print(l1)

[1,2,5],[3,4,7]]

Extend is for objects.
Append is what you need here.
gilch
Reply   •   2 楼
gilch    6 年前

使用 zip() 并行地迭代两个或多个事物使用 range() 在不需要索引的时候创建索引是不必要的。

xss = [[1,2],[3,4]]
ys = [5,7]

for xs, y in zip(xss, ys):
    xs.append(y)

print(xss)

[[1, 2, 5], [3, 4, 7]]
adrtam
Reply   •   3 楼
adrtam    6 年前

list1.extend(list2) 是要创建 list1+list2 . 但你没有提供 list2 相反,它只是一个元素。正确的功能是 list1.append(element2) ,与 list1+[element2]