Changed Nested list items to integer format - python

How do I filter or remove the .0 at the end of my numbers? I tried converting them to integers but lists don't allow that. Is regex my best option? I don't need to do any maths with the numbers. I just need to remove the .0 at the end.
all help welcome.
Nums = [['17001.0', '17001.0'], ['17001.0', '11001.0'], ['17001.0', '18001.0'], ['17001.0', '19001.0'],
['14001.0', '12001.0'], ['19001.0', '18001.0'], ['19001.0', '16001.0'], ['15001.0'], ['16001.0'],
['18001.0'], ['19001.0'], ['18001.0'], ['22.0'], ['22.0'], ['22.0'], ['19001.0']]

If you want list with integer elements then this may help you:
Nums = [['17001.0', '17001.0'], ['17001.0', '11001.0'], ['17001.0', '18001.0']]
a=[]
for c in Nums:
if len(c)>1:
for d in c:
a.append(int(float(d)))
else:
a.append(int(float(c)))
# a= [17001, 17001, 17001, 11001, 17001, 18001]

I believe this would be the simplest approach:
nozeros = []
for i in Nums:
nozeros.append([int(j.split('.')[0]) for j in i])

I tried converting them to integers byt lists don't alow that
That's completely wrong:
IntNums = []
for lst in Nums:
IntLst = []
for n in lst:
IntLst.append(int(float(n)))
IntNums.append(IntLst)
You couldn't convert strings into integers because they contained the '.0' suffix, but you could first convert them to floats and then to integers.
If you want to convert the list in place, you iterate using indices:
for i in range(len(Nums)):
for j in range(len(Nums[i])):
Nums[i][j] = int(float(Nums[i][j]))
You could use a list comprehension too:
Nums = [[int(float(n)) for n in lst] for lst in Nums]

Related

How to sort list of strings

I have an initial list of strings:
List1 = ["2,6,4,5", "3,7,4,2"]
I would like each string to be sorted in ascending order:
Output = ["2,4,5,6", "2,3,4,7"]
May I know how do I do that?
You can try splitting, sort, then join
List1 = ["2,6,4,5", "3,7,4,2"]
sortedList = []
for s in List1:
nums = s.split(",")
nums.sort()
sortedList.append(",".join(nums))
Thanks for pointing out that the above doesn't work for numbers > 10 and negative numbers, I forgot that it was sorting with strings. Although the question didn't really specify, it makes sense that sorting should be based on number rather than string so update:
for s in List1:
nums = s.split(",")
nums = list(map(int, nums))
nums.sort()
nums = list(map(str, nums))
sortedList.append(",".join(nums))
You could make use of ast.literal_eval in order to evaluating the strings as Python values:
import ast
List1 = ["2,6,4,5", "3,7,4,2"]
print([",".join(map(str, sorted(ast.literal_eval(item)))) for item in List1])
Out:
['2,4,5,6', '2,3,4,7']
Here's a way to do it using list comprehension
List1 = ["2,6,4,5", "3,7,4,2"]
Output = [','.join(sorted(lis)) for lis in [s.split(',') for s in List1]]
['2,4,5,6', '2,3,4,7']

Trying to replace a list of strings consisting of integers into the sum of their digits- but running into type error

I have a list of strings consisting of integers, and I am trying to replace them with the sum of their digits. E.g. nums = ["12","23","33"] -> nums = [3,5,6]
Here is my code:
strng = ['12','23','33']
for i in range(len(strng)):
print(list((map(lambda x:int[x],list(strng[i])))))
For the above I am getting a TypeError: 'type' object is not subscriptable. It works up until map(), but when I add the list(map(...)), I get this error.
Any ideas how to fix it?
My after this is fixed, my idea is to do the following:
strng = ['12','23','33']
for i in range(len(strng)):
strng[i] = sum(list((map(lambda x:int[x],list(strng[i]))))))
Which should replace each of strng with the sum of its digits.
The error you're getting is you because you wrote int[x] instead of int(x). However, there are some additional issues with your existing solution.
The short and pythonic solution to this problem would be:
answer = [sum(map(int, list(s))) for s in strng]
To break this down:
[... for s in strng]: this is a list comprehension
list(s): This takes each string and converts it into a list of str of each character, so "123" becomes ["1","2","3"]
map(int, list(s)): This applys the int conversion to each element in list(s), so ["1","2","3"] becomes [1,2,3]
sum(...): We take the sum of the resulting list of ints
The equivalent of the above using a normal for loop would be something like this:
answer = []
for s in strng:
list_of_chars = list(s)
list_of_ints = map(int, list_of_chars)
sum_of_ints = sum(list_of_ints)
answer.append(sum_of_ints)
You can use comprehension, and iterate each digits, convert them to integer, finally pass it to sum builtin to get sum of the values.
>>> [sum(int(i) for i in v) for v in strng]
[3, 5, 6]
Not really efficient, but try this :
strng = ['12','23','33']
def function(strng) :
my_list = []
for string in strng :
my_list.append(0)
for digit in string :
my_list[-1] += int(digit)
return my_list
strng = function(strng)
print(strng)

How to remove strings from a list of list of integers?

I have a list of lists of integers and strings and I want to remove the strings. How would I go about doing this?
a = [[1,2,3,4,5,'test'], [6,7,84,3,2,4,'nan'], [4,1,2,4,5,42,4,'test']]
I have tried the following
for i in a:
for e in i:
if isinstanece(e, str) == True:
a.remove(e)
Nested list comprehensions will achieve what you're looking for.
[[val for val in lst if isinstance(val,int)] for lst in a]
edit: You could also check that the value is not a string:
[[val for val in lst if not isinstance(val,str)] for lst in a]

How to remove characters from each element in a list

I would like to remove the first two characters from each element (which are currently ints) that i have in a list. This is what i have:
lst = [2011,2012,3013]
I would like to get this
lst= [11,12,13]
I do not want a solution with some sort of replace 20 or 30 with '' however.
Given source= [2011,-2012,-3013] :
Result as ints, unsigned:
dest = [abs(x)%100 for x in source]
Result as ints, signed
dest = [(abs(x)%100)*(1 if x > 0 else -1) for x in source]
Result as strings, unsigned (preserves leading zeroes):
dest = list(map(lambda x : str(x)[-2:],source)
Result as strings, signed (preserves leading zeroes):
dest = list(map(lambda x : ("-" if str(x)[0]=="-" else "")+str(x)[-2:],source))
You can use:
list = [abs(number)%100 for number in list]
And it's a bad practice to name lists list. Use another name.
You can use module by 100,like:
my_list= [2011,2012,3013]
expected_list = [i%100 for i in my_list]
If you have negative numbers in my_list:
expected_list=[abs(i)%100 for i in my_list]
Or use string slicing:
expected_list = [int(str(i)[2:]) for i in my_list] #[2:],because you want to remove first two numbers
Please try avoid using reserved keywords as you variable name, as you have used list as your variable name.
Modulo:
just modulo each element with like 100
list= [2011,2012,3013]
for i in range(len(list)):
list[i] %= 100

How to merge n lists together item by item for each list

I want to make one large list for entering into a database with values from 4 different lists. I want it to be like
[[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]], etc.....]
Another issue is that currently the data is received like this:
[ [ [list1[0], list1[1], [list1[3]]], [[list2[0]]], etc.....]
I've tried looping through each list using indexs and adding them to a new list based on those but it hasn't worked, I'm pretty sure it didn't work because some of the lists are different lengths (they're not meant to be but it's automated data so sometimes there's a mistake).
Anyone know what's the best way to go about this? Thanks.
First list can be constructed using zip function as follows (for 4 lists):
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]
list4 = [13,14,15,16]
res = list(zip(list1,list2,list3,list4))
For arbitrtary number of lists stored in another list u can use *-notation to unpack outer list:
lists = [...]
res = list(zip(*lists))
To construct list of lists for zipping from you data in second issue use flatten concept to it and then zip:
def flatten(l):
res = []
for el in l:
if(isinstance(el, list)):
res += flatten(el)
else:
res.append(el)
return res
auto_data = [...]
res = list(zip(*[flatten(el) for el in auto_data]))
Some clarification at the end:
zip function construct results of the smallest length between all inputs, then you need to extend data in list comprehension in last code string to be one length to not lose some info.
So if I understand correctly, this is your input:
l = [[1.1,1.2,1.3,1.4],[2.1,2.2,2.3,2.4],[3.1,3.2,3.3,3.4],[4.1,4.2,4.3,4.4]]
and you would like to have this output
[[1.1,2.1,3.1,4.1],...]
If so, this could be done by using zip
zip(*l)
Make a for loop which only gives you the counter variable. Use that variable to index the lists. Make a temporary list , fill it up with the values from the other lists. Add that list to the final one. With this you will et the desired structure.
nestedlist = []
for counter in range(0,x):
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
If all the 4 lists are the same length you can use this code to make it even nicer.
nestedlist = []
for counter in range(0,len(firstlist)): #changed line
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
This comprehension should work, with a little help from zip:
mylist = [i for i in zip(list1, list2, list3, list4)]
But this assumes all the list are of the same length. If that's not the case (or you're not sure of that), you can "pad" them first, to be of same length.
def padlist(some_list, desired_length, pad_with):
while len(some_list) < desired_length:
some_list.append(pad_with)
return some_list
list_of_lists = [list1, list2, list3, list4]
maxlength = len(max(list_of_lists, key=len))
list_of_lists = [padlist(l, maxlength, 0) for l in list_of_lists]
And now do the above comprehension statement, works well in my testing of it
mylist = [i for i in zip(*list_of_lists)]
If the flatten concept doesn't work, try this out:
import numpy as np
myArray = np.array([[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]]])
np.hstack(myArray)
Also that one should work:
np.concatenate(myArray, axis=1)
Just for those who will search for the solution of this problem when lists are of the same length:
def flatten(lists):
results = []
for numbers in lists:
for output in numbers:
results.append(output)
return results
print(flatten(n))

Categories