📌  相关文章
📜  Python程序输入逗号分隔的字符串

📅  最后修改于: 2022-05-13 01:55:35.942000             🧑  作者: Mango

Python程序输入逗号分隔的字符串

给定一个以逗号而不是空格分隔的输入字符串。任务是将此输入字符串存储在列表或变量中。这可以通过两种方式在Python中实现:

  • 使用列表理解和split()
  • 使用map()split()

方法一:使用列表推导和split()

split()函数有助于从用户那里获得多个输入。它通过指定的分隔符打破给定的输入。如果未提供分隔符,则使用任何空格作为分隔符。通常,用户使用split()方法来拆分Python字符串,但也可以使用它来获取多个输入。

例子:

# Python program to take a comma
# separated string as input
  
  
# Taking input when the numbers 
# of input are known and storing
# in different variables
  
# Taking 2 inputs
a, b = [int(x) for x in input("Enter two values\n").split(', ')]
print("\nThe value of a is {} and b is {}".format(a, b))
  
# Taking 3 inputs
a, b, c = [int(x) for x in input("Enter three values\n").split(', ')]
print("\nThe value of a is {}, b is {} and c is {}".format(a, b, c))
  
# Taking multiple inputs
L = [int(x) for x in input("Enter multiple values\n").split(', ')]
print("\nThe values of input are", L) 

输出:

Enter two values
1, 2

The value of a is 1 and b is 2
Enter three values
1, 2, 3

The value of a is 1, b is 2 and c is 3
Enter multiple values
1, 22, 34, 6, 88, 2

The values of input are [1, 22, 34, 6, 88, 2]

方法二:使用map()split()

map()函数在将给定函数应用于给定迭代(列表、元组等)的每个项目后返回结果列表

# Python program to take a comma
# separated string as input
  
  
# Taking input when the numbers 
# of input are known and storing
# in different variables
  
# Taking 2 inputs
a, b = map(int, input("Enter two values\n").split(', '))
print("\nThe value of a is {} and b is {}".format(a, b))
  
# Taking 3 inputs
a, b, c = map(int, input("Enter three values\n").split(', '))
print("\nThe value of a is {}, b is {} and c is {}".format(a, b, c))
  
# Taking multiple inputs
L = list(map(int, input("Enter multiple values\n").split(', ')))
print("\nThe values of input are", L)

输出:

Enter two values
1, 2

The value of a is 1 and b is 2
Enter three values
1, 2, 3

The value of a is 1, b is 2 and c is 3
Enter multiple values
1, 2, 3, 4

The values of input are [1, 2, 3, 4]