加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

附加到Python列表而不制作列表列表

发布时间:2020-12-20 12:19:57 所属栏目:Python 来源:网络整理
导读:我从一个空列表开始,并提示用户输入一个短语.我想将每个字符添加为数组的单个元素,但我这样做的方式会创建一个列表列表. myList = []for i in range(3): myPhrase = input("Enter some words: ") myList.append(list(myPhrase)) print(myList) 我明白了: En
我从一个空列表开始,并提示用户输入一个短语.我想将每个字符添加为数组的单个元素,但我这样做的方式会创建一个列表列表.

myList = []
for i in range(3):
    myPhrase = input("Enter some words: ")
    myList.append(list(myPhrase))
    print(myList)

我明白了:

Enter some words: hi bob
[['h','i',' ','b','o','b']]

Enter some words: ok
[['h','b'],['o','k']]

Enter some words: bye
[['h','k'],['b','y','e']]

但我想要的结果是:

['h','b' ... 'o','k','e']

解决方法

.append()的参数不会以任何方式扩展,提取或迭代.如果希望将列表的所有单个元素添加到另一个列表,则应使用.extend().

>>> L = [1,2,3,4]
>>> M = [5,6,7,8,9]
>>> L.append(M)    # Takes the list M as a whole object
>>>                # and puts it at the end of L
>>> L
[0,1,[5,9]]
>>> L = [1,4]
>>> L.extend(M)    # Takes each element of M and adds 
>>>                # them one by one to the end of L
>>> L
[0,5,9]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读