Find List2 in List1 at starting Position - python

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']

Related

Removing strings from a list dependent on their length?

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))

List of Strings to Strings

How can I turn this
list = [['I','am','a','hero'],['What','time','is','it']]
to this
list = [["I am a hero"],["What time is it"]]
This doesn't work:
list(chain.from_iterable(list.str.split(',')))
And neither does:
[a for a in list]
You could join the list items:
list1 = [['I', 'am', 'a', 'hero'], ['What', 'time', 'is', 'it']]
list2 = [[' '.join(item)] for item in list1]
print(list2)
Output:
[['I am a hero'], ['What time is it']]
Here is one way of doing it
lst = [['I','am','a','hero'],['What','time','is','it']]
new_list = [[' '.join(x)] for x in lst]
print(new_list)

Python list in list with 2 strings

I have 2 lists of strings. I would like to combine them together to create list in lists like this one below.
[['Hello','praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]
How to do it? Somehow create instance of list in list or there is some "python magic"?
Thank you
zip (Python Docs) is what you are looking for. You can stitch together two lists in a list comprehension:
l1 = ['Hello', 'world']
l2 = ['praet:sg:m1:perf','subst:pl:acc:n']
zipped = [list(items) for items in zip(l1,l2)]
print(zipped)
Result:
[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]
There are many ways to do that.
ex-1: by using '+'
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
print([list1]+[list2])
ex-2: by using append()
res =[]
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
res.append(list1)
res.append(list2)
print(res)
ex-3: by using zip()
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
res = [[l1, l2] for l1,l2 in zip(list1, list2)]
print(res)
I hope this helps:
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
newlist = []
for i in range(len(list1)):
newlist.append([list1[i],list2[i]])
Just add the two list you have to another list:
list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']
result = [list1, list2]
Another way:
result = []
list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']
...
result.append(list1)
result.append(list2)
Use zip
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
result = [[x, y] for x,y in zip(list1, list2)]
print(result)
Output:
[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]

Substring filter list elements by another list in Python

I have two lists looking like:
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
I want to substring filter list1 by elements of list2 and get expected output as follows:
outcome = ['bj-100-cy', 'sh-200-pd']
When doing:
list1 = str(list1)
list2 = str(list2)
outcome = [x for x in list2 if [y for y in list1 if x in y]]
I get a result like this: ['[', '1', '0', '0', ',', ' ', '2', '0', '0', ']'].
How can I filter it correctly? Thanks.
Reference related:
Is it possible to filter list of substrings by another list of strings in Python?
List comprehension and any:
[i for i in list1 if any(i for j in list2 if str(j) in i)]
any to check if any element of list2 is a substring of the list1 item (__contains__) being iterated over.
Example:
In [92]: list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
...: list2 = [100, 200]
...:
In [93]: [i for i in list1 if any(i for j in list2 if str(j) in i)]
Out[93]: ['bj-100-cy', 'sh-200-pd']
You can use any:
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
list2 = [str(x) for x in list2]
outcome = [s for s in list1 if any(x in s for x in list2)]
any returns True if any of the conditions you give it are True.
list1 = str(list1)
list2 = str(list2)
You are converting your list into a string with the above statements. So when you iterate in a for loop, you are iterating each characters, instead of each word.
So you should remove string conversion and instead do a list comprehension as follows.
Also, in your outcome file instead of checking if the word in list2 is in list1, you are checking the opposite. So you got like 100 and 200 as chars which are in list 2.
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
outcome = [x for x in list1 for y in list2 if str(y) in x]
You can try this one:
list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
list2 = [100, 200]
outcome = []
for item in list1:
if any(str(i) in item for i in list2):
outcome.append(item)
output:
['bj-100-cy', 'sh-200-pd']
Another alternative list comprehension :
>>> list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
>>> list2 = [100, 200]
>>> occur = [i for i in list1 for j in list2 if str(j) in i]
>>> occur
['bj-100-cy', 'sh-200-pd']
You can use builtin filter method to filter the list based on your condition. Your condition requires python in operator to search for needle([100, 200]) in haystack ([['bj-100-cy','bj-101-hd',...]]).
We can use contains method to simplify search syntax.
Code
from operator import contains
filter(lambda x: any(contains(x,str(y)) for y in list2), list1)
Example
>>> list1 = ['bj-100-cy','bj-101-hd','sh-200-pd','sh-201-hp']
>>> list2 = [100, 200]
>>> for item in filter(lambda x: any(contains(x,str(y)) for y in list2), list1):
... print(item)
...
bj-100-cy
sh-200-pd
You can use regex:
import re
list1 = ['bj-100-cy', 'bj-101-hd', 'sh-200-pd', 'sh-201-hp']
list2 = [100, 200]
pattern = re.compile('|'.join(map(str, list2)))
list(filter(pattern.search, list1))
# ['bj-100-cy', 'sh-200-pd']

How to remove items from a list if they match any items in another list in Python

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

Categories