首页 > 解决方案 > 对于给定的两个序列,我在编写程序以组合两个序列并按字母顺序排列时遇到输入错误?

问题描述

def all_people(people_1, people_2):
    # update logic here
    people_1.split(',')
    people_2.split(',')
    people_1.extend(people_2)
    print(people_1.sort())

people_1 = input()
people_2 = input()

all_people(people_1, people_2)

对于给定的两个序列,我得到一个 AttributeError: 'str' object has no attribute 'extend' 问题是:如何编写一个程序来组合两个序列并按字母顺序排列它们。

标签: python-3.x

解决方案


str.split不会将拆分的字符串转换为列表(即使没有类型差异,字符串也是不可变的),而是返回一个列表。要使用它,您需要将它分配给一个变量。如果您不需要原始字符串,则可以覆盖它1

list_1 = input('first list, separated by , -> ')
list_1 = list_1.split(',')
list_2 = input('second list, separated by , -> ').split(',')

list_1.extend(list_2)
print(list_1)

会导致

first list, separated by , -> a,b,some value with spaces
second list, separated by , -> in,the,second,one
['a', 'b', 'some value with spaces', 'in', 'the', 'second', 'one']

1这适用于转换数据结构一次的简单情况。不要到处用完全不相关的东西覆盖变量。


推荐阅读