Python issue with list and join function - python

How do I append two digit integer into a list using for loop without splitting them. For example I give the computer 10,14,13,15 and I get something like 1,0,1,4,1,3,1,5. I tried to go around this, but I ended up with a new issue, which is Type Error: sequence item 0: expected string, int found
def GetNumbers(List):
q=[]
Numberlist = []
for i in List:
if i.isdigit():
q.append(int(i))
else:
Numberlist.append(''.join(q[:]))
del q[:]
return Numberlist

Ideal way will be to use str.split() function as:
>>> my_num_string = "10,14,13,15"
>>> my_num_string.split(',')
['10', '14', '13', '15']
But, since you mentioned you can not use split(), you may use regex expression to extract numbers from string as:
>>> import re
>>> re.findall('\d+', my_num_string)
['10', '14', '13', '15']
Else, if you do not want to go with any fancy method, you may achieve it with simple for loop as:
num_str, num_list = '', []
# ^ Needed for storing the state of number while iterating over
# the string character by character
for c in my_num_string:
if c.isdigit():
num_str += c
else:
num_list.append(num_str)
num_str = ''
The numbers in num_list will be in the form of str. In order to convert them to int, you may explicitly convert them as:
num_list = [int(i) for i in num_list] # OR, list(map(int, num_list))

Related

Converting Strings to int in List [duplicate]

This question already has answers here:
Convert all strings in a list to int
(10 answers)
Closed last month.
have a list with numeric strings, like so:
numbers = ['1', '5', '10', '8'];
I would like to convert every list element to integer, so it would look like this:
numbers = [1, 5, 10, 8];
The natural Python way of doing this is using list comprehensions:
intlist = [int(element) for element in stringlist]
This syntax is peculiar to the Python language and is a way to perform a "map" with an optional filtering step for all elements of a sequnce.
An alterantive way, which will be more familiar for programmers that know other languages is to use the map built-in: in it, a function is passed as the first parameter, and the sequence to be processed as the second parameter. The object returned by map is an iterator, that will only perform the calculations on each item as it is requested. If you want an output list, you should build a list out of the object returned by map:
numbers = list(map(int, stringlist))
You can use a simple function called map:
numbers = ['1', '5', '10', '8']
numbers = list(map(int, numbers))
print(numbers)
This will map the function int to each element in the iterable. Note that the first argument the map is a function.
you can use generator objects
[int(i) for i in numbers]
Sometimes int() gives convertion error if the input it's not a valid variable. In that case must create a code that wraps all convertion error.
numbers = []
not_converted = []
for element in string_numbers:
try:
number = int(element)
if isinstance(number, int):
numbers.append(number)
else:
not_converted.append(element)
except:
not_converted.append(element)
If you expect that the input it's aways a string int you can simply convert like:
numbers = [int(element) for element in string_numbers]
You can use the below example:-
numbers = ['3', '5', '7', '9']
numbers = list(map(int, numbers))
print(numbers)

How can i convert user enter number into list in python? Like user entered 56989 and i want these number separately in list{5,6,9,8,9}

Because i wanna make a program for reverse of number entered by user .So after getting number into list,will do indexing to get reversal of that number entered by user.If Yes so How??or No so what is the other method.
#reverse of a number
num = int(input("Enter a number"))
list = [num]
print(list)
list[3]
print(list)
Assuming the user entered "12345", doing
my_list = list(input("Enter a number"))
Would give you a list ['1', '2', '3', '4', '5'] (of strings)
If you just want to reverse it and print it, there are several ways. To reverse it we can my_list = my_list[::-1] for example. The more readable way we can use to reverse it "in-place":
my_list.reverse()
Either way, we now have a list that is ['5', '4', '3', '2', '1']
You can just print that, but I assume you want to turn it back into a string, we can do that with
my_str = ''.join(my_list)
Putting it all together:
my_list = list(input("Enter a number"))
my_list.reverse()
my_str = ''.join(my_list)
print(my_str)
Would print the reverse of anything the user entered (doesn't have to be numbers, there's a whole other verification we need for that). As was mentioned by #FraggaMuffin in a comment, this can all be done in one line (by using the built-in reversed function, avoiding the list altogether):
print(''.join(reversed(input("Enter a number"))))
Notice however the most important thing, we didn't use the word list as a variable, because that would destroy the built-in list, that's why it's called my_list in my example, same with str and my_str
I hope this helps you
use list() amd map() function. use a[::-1] to reverse the list.
a =list(map(int,input()))
print(a)
print(a[::-1])
print(a[2])
Input:
56989
Output:
[5,6,9,8,9] /normal list /
[9,8,9,6,5] /reversed list /
9 /accesing the reversed list /

Split an element at whitespace in python 2

I have a text dump of letters and numbers, and I want to filter out only valid credit card numbers (for class, I swear). I used
for item in content:
nums.append(re.sub('[^0-9]', ' ', item))
to take out everything that isn't a number, so I have a list of elements that are numbers with white space in the middle. If I don't turn the non-int characters into spaces, the numbers end up concatenated so the lengths are wrong. I want to split each element into a new element at the whitespace.
Here's a screenshot of part of the Sample output, since I can't copy it without python turning every group of multiple spaces into a single space: https://gyazo.com/4db8b8b78be428c6b9ad7e2c552454af
I want to make a new element every time there is one or more spaces. I tried:
for item in nums:
for char in item:
char.split()
and
for item in nums:
item.split()
but that ended up not changing anything.
split doesn't mutate the string but returns a list of strings instead. If you call it without storing the result as in your example it won't do anything good. Just store the result of split to new list:
>>> nums = ['1231 34 42 432', '12 345345 7686', '234234 45646 435']
>>> result = []
>>> for item in nums:
... result.extend(item.split())
...
>>> result
['1231', '34', '42', '432', '12', '345345', '7686', '234234', '45646', '435']
Alternatively you could use list comprehension to do the above on one line:
>>> [x for item in nums for x in item.split()]
['1231', '34', '42', '432', '12', '345345', '7686', '234234', '45646', '435']

why sort in python is not working?

code:
list=['1','85863','432','93','549834']
list.sort()
print (list)
Actual output:
>>>
['1', '432', '549834', '85863', '93']
#why sort is not working
Expected output:
['1','93','432','83863','549834']
I have tried other sort operations also but they are displaying same output.
when i tried to read list from keyboard input they are reading only strings but not int please help me why?
when i tried to read list from keyboard input they are reading only strings but not int please help me why
if x is a string, just use int(x) to convert to int
You're sorting strings (text), not by numerical values like integers
For your expected output you have to convert to ints first
my_list= ['1','85863','432','93','549834']
my_list = [int(x) for x in my_list]
Now you can sort numerically, and get a list of ints
my_list.sort()
N.B. avoid using list as variable name, it is a Python built-in
I presume you want to sort by the sum to match your expected output:
l = ['1','85863','432','93','549834']
l.sort(key=lambda x: sum(map(int,x)))
print(l)
['1', '432', '93', '83863', '549834']
You need to first convert the strings to int.
list = [int(ele) for ele in list]
list.sort()
print list
Without int:
lst = ['1','85863','432','93','549834']
lst.sort()
lst.sort(key=len)
print(lst)
This give:
['1', '93', '432', '85863', '549834']
And if you want integers…
my_int = int(input())
I simply missed the logic of converting a string into int.By default python input will be taken as a string. so,we can use any method mentioned in the answers to convert in to string and then sort() method works succesufully over int

How do I extract certain digits from raw input in Python?

Let's say I ask a users for some random letters and numbers. let's say they gave me 1254jf4h. How would I take the letters jfh and convert them inter a separate variable and then take the numbers 12544 and make them in a separate variable?
>>> s="1254jf4h"
>>> num=[]
>>> alpah=[]
>>> for n,i in enumerate(s):
... if i.isdigit():
... num.append(i)
... else:
... alpah.append(i)
...
>>> alpah
['j', 'f', 'h']
>>> num
['1', '2', '5', '4', '4']
A for loop is simple enough. Personally, I would use filter().
s = "1254jf4h"
nums = filter(lambda x: x.isdigit(), s)
chars = filter(lambda x: x.isalpha(), s)
print nums # 12544
print chars # jfh
edit: oh well, you already got your answer. Ignore.
NUMBERS = "0123456789"
LETTERS = "abcdefghijklmnopqrstuvwxyz"
def numalpha(string):
return string.translate(None, NUMBERS), string.translate(None, LETTERS)
print numalpha("14asdf129h53")
The function numalpha returns a 2-tuple with two strings, the first containing all the alphabetic characters in the original string, the second containing the numbers.
Note this is highly inefficient, as it traverses the string twice and it doesn't take into account the fact that numbers and letters have consecutive ASCII codes, though it does have the advantage of being easily modifiable to work with other codifications.
Note also that I only extracted lower-case letters. Yeah, It's not the best code snippet I've ever written xD. Hope it helps anyway.

Categories