python-3.x - 对于给定的两个序列,我在编写程序以组合两个序列并按字母顺序排列时遇到输入错误?
问题描述
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' 问题是:如何编写一个程序来组合两个序列并按字母顺序排列它们。
解决方案
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这适用于转换数据结构一次的简单情况。不要到处用完全不相关的东西覆盖变量。
推荐阅读
- angular - 如何在 Angular 中初始化单选按钮组的 value 属性?
- javascript - 带有内部图标的Javascript onclick动作问题
- spring - 在 Jenkins 构建的 docker 容器中设置正确的工作目录的问题
- android - 使用 enqueueUniquePeriodicWork 的 PeriodicWork 不起作用
- php - 删除匹配记录的 CSV 行
- java - 当软键盘可见时,CollapsingToolbarLayout 不会折叠
- android - 在 Cordova 上运行命令时出错:cordova emulate 命令
- c++ - 为什么我们在使用的时候一定要链接pthread
C++ 11 的? - node.js - 节点 glob 同步返回空数组
- javascript - Vuejs - 更新数组中的对象