If I were to ask someone to enter value:
value = input("List numbers: ")
and I wanted to organize it:
User Input = 1, 2, 3, 2
and get a print() of 1, 2, 3 as a result- getting rid of extra numbers
How would I go about doing that?
and also How would I organize them? for an example 2 1 4 3 5 and get a print() of 1 2 3 4 5
It seems you're looking for a list of sorted unique numbers. You can use sorted(set(map(int, value.split(",")))
to get that. See the Demo -
>>> 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(',')
splits the input list on ','
, thus returning a list of strings. map(int, ...)
converts each entry in the above list to an integer. set(...)
makes a set out of the above list, thus eliminating any duplicates. sorted(...)
sorts the set and produces a list. You could then use join(...)
method to convert it back into a string. If for example you wanted to seperate them with a ', '
, you could do
>>> ", ".join(map(str, sorted(set(map(int, value.split(',')))))) # Or use an equivalent List Comprehension.
'1, 2, 3, 4, 5'
Here is a step by step guide to
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
This code requires the user to use commas to separate values. This can be changed.
To do the same thing with strings try this
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.