Any Idea when I do the split on list( after converting to string) I am not getting the first and the last elements in the list....
if __name__ =="__main__":
lst1= ['3 6 2 5'];
lst1=str(lst1);
a = [int(i) for i in lst1.split(' ') if i.isdigit()]
print(a);
Outputs
[6, 2]
What I am looking for is
[2,3,5,6]
I think its due to the split characters which it finds after the 3(first element), but not sure how to resolve it.
When you convert lst1 to a string, you get
"['3 6 2 5']"
When you split this, you get the list: fir
["['3", "6", "2", "5']"]
"['3".isdigit() and "5']".isdigit() are false, so it doesn't print those elements.
To get the result you expect, you should not convert the list to a string. You should index the list to get its elements.
for s in lst1:
a = [int(i) for i in s.split(' ') if i.isdigit()]
print(a)
Try it.
lst1= ['3 6 2 5'];
a = [int(i) for i in lst1[0].split(' ') if i.isdigit()]
a.sort()
print(a)
Related
This is a list that I have [['1.0\n'],['2.0\n'],['3.0\n']] and I would like to convert them into integers 1 2 3 without comma separation and \n.
I'm not sure how to do this conversion as there's a list within a list and I don't really know how to get rid of \n altogether. Thanks.
if you want [[1], [2], [3]], you can try
lst = [['1.0\n'],['2.0\n'],['3.0\n']]
res = [[int(float(j.replace("\n", ""))) for j in i] for i in lst]
if you want [1, 2, 3], you can try
lst = [['1.0\n'],['2.0\n'],['3.0\n']]
res = [int(float(i[0].replace("\n", ""))) for i in lst]
Depends on whether you want rounding or not and or a new list. Is there a reason why you have a list in a list? But you'd do something like this
x = [['1.0\n'],['2.0\n']]
y = []
for item in x:
tmp = item[0].replace('\n','')
y.append(int(float(tmp)))
print(y)
There is a way:
ls=[['1.0\n'],['2.0\n'],['3.0\n']]
result=[]
for ll in ls:
[result.append(int(float(l.replace('\n','')))) for l in ll]
print(result)
Output: [1, 2, 3]
This code just works under this condition: [if every element in the list has \n]
Like Raya's answer, I use the int(float(l)) way, if every element has '.0', you can also use l.replace('\n','').replace('.0','').
Removing /n and consolidate to a single list
You could solve this with list comprehension.
list = [['1.0\n'], ['2.0\n'], ['3.0\n']]
my_list = [int(float(value[0].strip())) for value in list]
print(my_list)
Output: [1, 2, 3]
The main things to note in this solution are:
The nested lists are iterated through, selecting the first element of each with value[0].
Each iteration:
Value: '1.0\n' is stripped of the \n with value[0].strip()
Value: 1.0 is then converted to a float float(value[0].strip())
Value: 1 is then converted to a integer int(float(value[0].strip()))
Without comma separation
list = [['1.0\n'], ['2.0\n'], ['3.0\n']]
my_list = [int(float(value[0].strip())) for value in list]
my_string = " ".join(str(value) for value in my_list)
print(my_string)
Output: 1 2 3
I have a list which looks like below
lis = '[-3.56568247e-02 -3.31957154e-02\n 7.04742894e-02\n 7.32413381e-02\n 1.74463019e-02]' (string type)
'\n' is also there in the list.
I need to convert this to actual list of integers
lis = [-3.56568247e-02,-3.31957154e-02 ,7.04742894e-02 ,7.32413381e-02, 1.74463019e-02] (list of integers)
I am doing the functionality, but it is failing
import as
res = ast.literal_eval(lis)
Can anyone tell me how to resolve this?
We can use re.findall along with a list comprehension:
lis = '[-3.56568247e-02 -3.31957154e-02 7.04742894e-02 7.32413381e-02\n 1.74463019e-02]'
output = [float(x) for x in re.findall(r'\d+(?:\.\d+)?(?:e[+-]\d+)?', lis)]
print(output)
# [0.0356568247, 0.0331957154, 0.0704742894, 0.0732413381, 0.0174463019]
You can try
[int(i) for i in lis.strip("[]").split(" ")]
You risk getting 1000 ways to do this.
This is a quick and easy way using only basic methods:
lis = '[1 2 3 4 5 77]'
elements = lis.replace('[','').replace(']','').split(' ')
my_ints = [int(e) for e in elements]
print(my_ints)
i'm a python newbie and i want to check if a each list element is present in another list(while respecting the index) and append this element to a third list. like this. if first element of 'listy'("11-02-jeej") contains first element of list_of_dates ("11-02), i want this element "11-02-jeej" to be appended in the first list of a list of lists. the code below doesn't work for me :(
the output that i want from this code is :[["11-02-jeej"], [2apples], []]
but instead i get : [[], [], []]
thank you so much !
list_of_dates =["11-02,", "2", "5"]
listy = ["11-02-jeej", "2apples", "d44"]
length = len(list_of_dates)
lst = [[] for m in range(length)]
for i in range(len(list_of_dates)):
date = list_of_dates[i]
for j in range(len(listy)):
name = listy [j]
if date in name:
lst[m].append(name)
print(lst)
There are the following issues in your code:
The input has a comma in the first string: "11-02,". As you expect this to be a prefix, I suppose that trailing comma should not be there: "11-02"
The if statement should be inside the inner loop, since it needs the name variable that is assigned there.
m is not the correct index. It should be i, so you get: lst[i].append(name)
So here is your code with those corrections:
list_of_dates =["11-02", "2", "5"]
listy = ["11-02-jeej", "2apples", "d44"]
length = len(list_of_dates)
lst = [[] for m in range(length)]
for i in range(len(list_of_dates)):
date = list_of_dates[i]
for j in range(len(listy)):
name = listy [j]
if date in name:
lst[i].append(name)
print(lst)
Note that these loops can be written with list comprehension:
lst = [[s for s in listy if prefix in s] for prefix in list_of_dates]
Be aware that for the given example, "2" also occurs in "11-02-jeej", so you have both "11-02" and "2" giving a match, and so that will impact the result. If you wanted "2" to only match with "2apples", then you may want to test a match only at the start of a string, using .startswith().
Say I have a string: line = "[1, 2, 12]\n"
and I want to convert it to a list of ints: [1, 2, 12]
I have the solution:
new_list = []
for char in line:
try:
new_list.append(int(char))
except ValueError:
pass
But this doesn't work in the case of numbers with more than one digit. Is there an inbuilt/better way to do this? Thanks
new_list = [int(num) for num in line.strip('[]\n').split(', ')]
A more readable solution will be:
line = line.strip('[]\n')
list_of_strs = line.split(', ')
list_of_nums = []
for elem in list_of_strs:
list_of_nums.append(int(elem))
First line is stripped of the enclosing brackets and newline characters. Then the remaining string is split on commas and the result is saved in a list. Now we have a list of elements where each number is still a string. Then the for loop converts each of the string element into numbers.
You can use regex:
import re
line = "[1, 2, 12]\n"
new_list = []
for char in re.findall("\d+", line):
try:
new_list.append(int(char))
except ValueError:
pass
print(new_list)
result: [1, 2, 12].
Regex and list comprehension:
The regex: \d+ will one or more repetitions (+) or the previous RE so in this case a digit (\d). So, we can use this on your string by finding all matches for this with re.findall().
However, this will return a list of the ints: 1, 2 and 12 but as strings so we can use a list comprehension to convert these into the type int.
Your code could look something like this:
import re
s = "[1, 2, 12]\n"
l = [int(i) for i in re.findall("\d+", s)]
print(l)
This will give the list: [1, 2, 12]
These commands:
l = ["1\n2"]
print(l)
print
['1\n2']
I want to print
['1
2']
Is it possible when we generate the list outside of the print() command?
A first attempt:
l = ["1\n2"]
print(repr(l).replace('\\n', '\n'))
The solution above doesn't work in tricky cases, for example if the string is "1\\n2" it replaces, but it shouldn't. Here is how to fix it:
import re
l = ["1\n2"]
print(re.sub(r'\\n|(\\.)', lambda match: match.group(1) or '\n', repr(l)))
Only if you are printing the element itself (or each element) and not the whole list:
>>> a = ['1\n2']
>>> a
['1\n2']
>>> print a
['1\n2']
>>> print a[0]
1
2
When you try to just print the whole list, it prints the string representation of the list. Newlines belong to individual elements so get printed as newlines only when print that element. Otherwise, you will see them as \n.
You should probably use this, if you have more than one element
>>> test = ['1\n2', '3', '4\n5']
>>> print '[{0}]'.format(','.join(test))
[1
2,3,4
5]
Try this:
s = ["1\n2"]
print("['{}']".format(s[0]))
=> ['1
2']