I have multiple lists of strings, inside a list. I want to change the strings that are digits into integers.
ex:-
L1=[['123','string','list']['words','python','456']['code','678','links']]
What i want is:
[[123,'string','list']['words','python',456]['code',678,'links']]
I have tried using-
W=range(len(L1))
Q=range(2)
if (L1[W][Q]).isdigit():
(L1[W][Q])=(int(L1[W][Q]))
when I tried the above code, I got an error.
Use str.isdigit():
L1=[['123','string','list'],['words','python','456'],['code','678','links']]
for item in L1:
for i in range(0,len(item)):
if(item[i].isdigit()):
item[i] = int(item[i])
print(L1)
Something like this:
>>> mylist = [['123','string','list'], ['words','python','456'], ['code','678','links']]
>>> [ [(int(item) if item.isdigit() else item) for item in sublist] for sublist in mylist]
[[123, 'string', 'list'], ['words', 'python', 456], ['code', 678, 'links']]
Related
I am trying to remove any strings from this list of strings if their length is greater than 5. I don't know why it is only removing what seems to be random strings. Please help. The item for sublist part of the code just changes the list of lists, into a normal list of strings.
list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist]
var=0
for words in li:
if len(li[var])>5:
li.pop()
var+=1
print(li)
The output is: ['name', 'number', 'continue', 'stop', 'signify']
Just include the check when flattening the list:
list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist if len(item) <= 5]
['name', 'stop', 'racer']
You can use a list comprehension to build a new list with only items that are 5 or less in length.
>>> l = ['123456', '123', '12345', '1', '1234567', '12', '1234567']
>>> l = [x for x in l if len(x) <= 5]
>>> l
['123', '12345', '1', '12']
list(filter(lambda x: len(x[0]) <= 5, list2))
List1 = ['RELEASE', 'KM123', 'MOTOR', 'XS4501', 'NAME']
List2 = ['KM', 'XS', 'M']
Now I am using code that only searches List2 in List1 in any position.
Result = [ s for s in List1 if any(xs in s for xs in List2]
Output :
[KM123', 'MOTOR', 'XS4501', 'NAME']
But I don't want 'NAME' to be in the list because it contains 'M' not in the starting. Any help...
Use str.startswith() which checks if a string starts with a particular sequence of characters:
[s for s in List1 if any(s.startswith(xs) for xs in List2)]
Looks like you can use str.startswith
Ex:
List1 = ['RELEASE', 'KM123', 'MOTOR', 'XS4501', 'NAME']
List2 = ('KM', 'XS', 'M') #convert to tuple
result = [ s for s in List1 if s.startswith(List2)]
print(result) #-->['KM123', 'MOTOR', 'XS4501']
list = [ 'u'adc', 'u'toto', 'u'tomato', ...]
What I want is to end up with a list of the kind:
list2 = [ 'adc', 'toto', 'tomato'... ]
Can you please tell me how to do that without using regex?
I'm trying:
for item in list:
list.extend(str(item).replace("u'",''))
list.remove(item)
but this ends up giving something of the form [ 'a', 'd', 'd', 'm'...]
In the list I may have an arbitrary number of strings.
you can encode it to "utf-8" like this:
list_a=[ u'adc', u'toto', u'tomato']
list_b=list()
for i in list_a:
list_b.append(i.encode("utf-8"))
list_b
output:
['adc', 'toto', 'tomato']
Or you can use str function:
list_c = list()
for i in list_a:
list_c.append(str(i))
list_c
Output:
['adc', 'toto', 'tomato']
Use "u\'"
For example:
l = [ "u'adc", "u'toto", "u'tomato"]
for item in l:
print(item.replace("u\'", ""))
Will output:
adc
toto
tomato
I verified your question but it says the syntax problem, which means that the way you are declaring the string in the list is not proper. In which case, I have corrected that at line #2.
In [1]: list = [ 'u'adc', 'u'toto', 'u'tomato']
File "<ipython-input-1-2c6e581e868e>", line 1
list = [ 'u'adc', 'u'toto', 'u'tomato']
^
SyntaxError: invalid syntax
In [2]: list = [ u'adc', u'toto', u'tomato']
In [3]: list = [ str(item) for item in list ]
In [4]: list
Out[4]: ['adc', 'toto', 'tomato']
In [5]:
Solution-1
input_list = [ u'adc', u'toto', u'tomato']
output_list=map(lambda x:str(x),input_list )
print output_list
And Output Look like:
['adc', 'toto', 'tomato']
Solution-2
input_list = [ u'adc', u'toto', u'tomato']
output_list=map(lambda x:x.encode("utf-8"),input_list )
print output_list
And Output Look like:
['adc', 'toto', 'tomato']
Try this:
for item in list:
for x in range(0, len(item)):
if item[x] == 'u':
item[x] = ''
This takes all instances in the list, and checks for the string 'u'. If 'u' is found, than the code replaces it with a blank string, essentially deleting it. Some more code could allow this to check for combinations of letters ('abc', etc.).
Your input is nothing but a json! You the dump each item in the list(which is a json!) to get the desired output!
Since your output comes with quotes - you need to strip(beginning and trailing) them!
import json
list = [ u'adc', u'toto', u'tomato']
print [json.dumps(i).strip('\"') for i in list]
Output:
['adc', 'toto', 'tomato']
Hope it helps!
How can I find a string in List1 that is a substring of any of the strings in List2? Both lists can be of different lengths.
Say I have:
List1=['hello', 'hi', 'ok', 'apple']
List2=['okay', 'never', 'goodbye']
I need it to return 'ok', seeing as it was the only string in list1 that matched list2.
You can use list comprehension as:
[x for x in List1 for y in List2 if x in y]
If you want to know if a string from list1 is in list2 you can do
for s in List1:
if s in List2:
print("found s in List2")
I wrote this piece of code to implement the
List1=['hello', 'hi', 'ok', 'apple']
List2=['ok', 'never', 'goodbye']
i=[]
for j in List1:
for k in List2:
if j==k:
i.append(j)
print i
Say I have two lists:
list1 = ['a', 'b']
list2 = ['cat', 'dog', 'bird']
Whats the best way to get rid of any items in list2 that contain any of the substrings in list1? (In this example, only 'dog' would remain.)
You can use list comprehension with any() operator. You go through the items of second list, if any of items(charachters) in list1 is in the selected word, we don't take it. Otherwise, we add it.
list1 = ['a', 'b']
list2 = ['cat', 'dog', 'bird']
print [x for x in list2 if not any(y for y in list1 if y in x)]
Output:
['dog']
You can use filter() as well.
print filter(lambda x: not any(y for y in list1 if y in x), list2)
You can use regular expressions to do the job.
import re
pat = re.compile('|'.join(list1))
res = []
for str in list2:
if re.search(pat, str):
continue
else:
res.append(str)
print res