I am fairly new to Python, and I am trying to create code that will return only even numbers from a list given from user input.
I had created this early on:
nums = input('Enter a sequence of numbers separated by commas: ')
lst = str.split(nums)
print(lst)
This returns what the user has given, but the commas will still be in the result. For instance, if I input: 5, 6, 7 ; it will come out as ['5,' , '6,' , '7'] On top of fixing this, I want to display only even numbers. I know I would have to check for this using %2 == 0, but I don't know how I would implement it.
First, you'll need to convert all your string items to integers. You can do this efficiently with a map
. After that, all you need to do is filter
out odd numbers.
filter(lambda x: x % 2 == 0, map(int, str.split(nums, ',')))
If you're using python3, convert the output to a list with list()
.
Demo:
>>> string = '2,5,8,12,5,6,7'
>>> list(filter(lambda x: x % 2 == 0, map(int, str.split(string, ','))))
[2, 8, 12, 6]
You can do this in two steps:
As a side note, if you want to split on commas in the user input, you need to explicitly tell str.split()
that.
>>> nums = input('Enter a sequence of numbers separated by commas: ')
Enter a sequence of numbers separated by commas: 1,2,3,4,5,6
>>> # Step 1
>>> lst = [int(n) for n in nums.split(',')]
>>> lst
[1, 2, 3, 4, 5, 6]
>>> # Step 2
>>> [n for n in lst if n % 2 == 0]
[2, 4, 6]
>>>
If you specify to split()
you want to split in the commas, you can do something using list comprehension as YiFei mentioned:
nums = input('Enter a sequence of numbers separated by commas: ')
lst = str.split(nums,',')
print([n for n in lst if (int(n)%2) == 0])
This gives:
Enter a sequence of numbers separated by commas: 2,5,8,10
['2', '8', '10']
Notice to convert n
into an int
when checking %2==0
.
this is because by default the split operation considers spaces as the delimiter. To solve this issue we need to nums.split(",") nums here is already a string. but even then you would get the white spaces to get rid of that, you'd require to replace all white spaces from the string before splitting them. For this purpose, you'd have to use nums.replace(" ", "") Then you have to parse each element in the resultant list to an integer, then see if its even and then append it on to the list
Convert the user input into integers using int(string number).
Since you are using a list to store your numbers you can do a loop through the list and check each element if it is even.
nums.split(',') is the correct syntax
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.