如何在 Python 中的一行中附加多个项目 [英] How to append multiple items in one line in Python

查看:42
本文介绍了如何在 Python 中的一行中附加多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

count = 0我 = 0而计数<伦(我的列表):如果 mylist[i + 1] == mylist[i + 13] 和 mylist[i + 2] == mylist[i + 14]:打印 mylist[i + 1], mylist[i + 2]newlist.append(mylist[i + 1])newlist.append(mylist[i + 2])newlist.append(mylist[i + 7])newlist.append(mylist[i + 8])newlist.append(mylist[i + 9])newlist.append(mylist[i + 10])newlist.append(mylist[i + 13])newlist.append(mylist[i + 14])newlist.append(mylist[i + 19])newlist.append(mylist[i + 20])newlist.append(mylist[i + 21])newlist.append(mylist[i + 22])计数 = 计数 + 1我 = 我 + 12

我想将 newlist.append() 语句变成几个语句.

解决方案

没有.追加整个序列的方法是list.extend().

<预><代码>>>>L = [1, 2]>>>L.extend((3, 4, 5))>>>升[1, 2, 3, 4, 5]

I have:

count = 0
i = 0
while count < len(mylist):
    if mylist[i + 1] == mylist[i + 13] and mylist[i + 2] == mylist[i + 14]:
        print mylist[i + 1], mylist[i + 2]
    newlist.append(mylist[i + 1])
    newlist.append(mylist[i + 2])
    newlist.append(mylist[i + 7])
    newlist.append(mylist[i + 8])
    newlist.append(mylist[i + 9])
    newlist.append(mylist[i + 10])
    newlist.append(mylist[i + 13])
    newlist.append(mylist[i + 14])
    newlist.append(mylist[i + 19])
    newlist.append(mylist[i + 20])
    newlist.append(mylist[i + 21])
    newlist.append(mylist[i + 22])
    count = count + 1
    i = i + 12

I wanted to make the newlist.append() statements into a few statements.

解决方案

No. The method for appending an entire sequence is list.extend().

>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]

这篇关于如何在 Python 中的一行中附加多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆