Python list in list with 2 strings - python

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

Related

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)

Find List2 in List1 at starting Position

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

How can I merge a list with a nested list?

I have two lists. The first one is a simple list with one entry:
l = [hello]
The second one is a nested list, with several thousand entries
i = [[world, hi],
[world, hi],
[world, hi],
[world, hi]]
Now I want to insert the entry from list l into the nested lists of i like this:
i = [[hello, world, hi],
[hello, world, hi],
[hello, world, hi],
[hello, world, hi]]
How can I do this?
You can use list comprehension to achieve that
i = [l+x for x in i]
Just use the insert method on each sublist in i.
for sublist in i:
sublist.insert(0, l[0])
If you don't want to modify i in place, and would prefer to build a new list, then
i = [[l[0], *sublist] for sublist in i]
simple: [[*l,*el] for el in i]
Output:
[['hello', 'world', 'hi'],
['hello', 'world', 'hi'],
['hello', 'world', 'hi'],
['hello', 'world', ' hi']]
I guess the benefits is that no matter how many elements you have in l, they will all be put in front of the stuff in i
Just add the element to the list you want
l = ["hello"]
i = [["world", "hi"],
["world", "hi"],
["world", "hi"],
["world", "hi"]]
x = []
for y in i:
x.append(l+y)
x
output:
[['hello', 'world', 'hi'],
['hello', 'world', 'hi'],
['hello', 'world', 'hi'],
['hello', 'world', 'hi']]
I believe something like this should do the trick:
l = ['hello']
i = [['world', 'hi'],
['world', 'hi'],
['world', 'hi'],
['world', 'hi']]
for j in i:
for k in l:
j = j.append(k)
I'm just iterating through your list i, nesting another for loop to iterate through the simpler list l (to account for the case whereby it has multiple elements), and simply appending each entry in l to the current list in i.

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