如果我要让某人输入值:
value = input("List numbers: ")
我想组织它:
用户输入 = 1、2、3、2
并得到一个 print() 的结果 1, 2, 3 - 摆脱多余的数字
我该怎么做呢?
还有我将如何组织它们?例如 2 1 4 3 5 并获得 print() 1 2 3 4 5
如果我要让某人输入值:
value = input("List numbers: ")
我想组织它:
用户输入 = 1、2、3、2
并得到一个 print() 的结果 1, 2, 3 - 摆脱多余的数字
我该怎么做呢?
还有我将如何组织它们?例如 2 1 4 3 5 并获得 print() 1 2 3 4 5
您似乎正在寻找已排序的唯一编号列表。你可以用它sorted(set(map(int, value.split(",")))
来获得。看演示 -
>>> value = raw_input("List numbers: ")
List numbers: 2, 1, 4, 3, 5, 3, 2, 4, 1
>>> sorted(set(map(int, value.split(','))))
[1, 2, 3, 4, 5]
value.split(',')
在 上拆分输入列表','
,从而返回字符串列表。map(int, ...)
将上面列表中的每个条目转换为整数。set(...)
从上面的列表中制作一个集合,从而消除任何重复。sorted(...)
对集合进行排序并生成一个列表。然后,您可以使用join(...)
方法将其转换回字符串。例如,如果您想用 a 将它们分开', '
,您可以这样做
>>> ", ".join(map(str, sorted(set(map(int, value.split(',')))))) # Or use an equivalent List Comprehension.
'1, 2, 3, 4, 5'
这是一步一步的指南
input = raw_input("Please enter your numbers separated by commas: ")
inputList = input.split(',') # creates a list from comma delimeters
intList = [int(i) for i in inputList] # converts to int list
uniqueList = set(intList) # removes duplicates
sortedList = sorted(uniqueList) # converts to ints and sorts
此代码要求用户使用逗号分隔值。这可以改变。
用字符串做同样的事情试试这个
input = raw_input("Please enter your words separated by commas: ")
inputList = input.split(',') # creates a list from comma delimeters
uniqueList = set(inputList) # removes duplicates
sortedList = sorted(uniqueList) # converts to ints and sorts