我的for循环是将输出作为拆分字符返回,而不是整个字符串或整数

My for loop is returning the output as split characters instead of whole strings or integers

提问人:Dinma 提问时间:10/26/2023 最后编辑:001Dinma 更新时间:10/26/2023 访问量:41

问:

第一个列表由输入创建,并附加一个新列表,该列表也由输入函数带到第一个列表。但是输出是拆分的,不是整个字符串,而是字符串的元素。对于整数列表或混合类型列表也是如此。它将所有内容拆分为单独的字符。 我使用什么函数或方法来阻止这种情况,谢谢。

我该怎么办?

输入

list1 = list(input("Enter the list: "))
list2 = list(input("Enter new list: "))

for i in list2:
    list1.append(i)
print(list(list1))

输出-

Enter the list: Joy, Adam, Ben, James
Enter new list: Dave, Ada, Elle

['J', 'o', 'y', ',', ' ', 'A', 'd', 'a', 'm', ',', ' ', 'B', 'e', 'n', ',', ' ', 'J', 'a', 'm', 'e', 's', 'D', 'a', 'v', 'e', ',', ' ', 'A', 'd', 'a', ',', ' ', 'E', 'l', 'l', 'e']
Python 列表 方法 数据分析

评论

1赞 Tim Roberts 10/26/2023
你期待什么?你没有在这里使用。您正在转换为列表。将字符串转换为列表时,每个元素将获得一个字符。split
0赞 Dinma 10/26/2023
我认为在输入函数之前使用的 list() 类型转换应该这样做,告诉 python 引入的任何项目都是列表的一部分,而不是字符串?
0赞 Tim Roberts 10/26/2023
不。 一次从其参数中提取一个元素,在本例中为 .如果要拆分某个字符的字符串,则使用 .list('abcd')['a','b','c','d']split

答:

2赞 Tim Roberts 10/26/2023 #1

我怀疑你是想使用,即使你没有使用它,你也描述了它:split

list1 = input("Enter the list: ").split(', ')
list2 = input("Enter new list: ").split(', ')
list1 += list2
print(list1)

输出:

Enter the list: One, Two, Three
Enter new list: Four, Five, Six
['One', 'Two', 'Three', 'Four', 'Five', 'Six']

评论

0赞 Dinma 10/26/2023
谢谢。它奏效了,这是我所做的 list1 = list(input(“输入列表:”).split(', ')) list2 = list(input(“输入新列表:”).split(', ')) for i in list2: list1.append(i) print(list(list(list1))
0赞 Tim Roberts 10/26/2023
你不需要那些演员表。 返回一个列表,当您打印时,已经是一个列表。取下石膏。以我为榜样。splitlist1