Swap position of entities in the list - python

I have a following example list
x= [['True_304', 'false_2'], ['True_702', 'false_2_1'], ['True_204', 'false_222_2']]
I would like to swap the positions of entities so that the second entity is first and first one is second. Basically, something like:
x= [['false_2', 'True_304'], ['false_2_1', 'True_702'], ['false_222_2', 'True_204']]
Is there any easier way to do this? Any ideas would be helpful. Thanks.

You can use list comprehensions:
>>> x = [['True_304', 'false_2'], ['True_702', 'false_2_1'], ['True_204', 'false_222_2']]
>>> [[b, a] for [a, b] in x]
[['false_2', 'True_304'], ['false_2_1', 'True_702'], ['false_222_2', 'True_204']]

And in case your list is larger than 2, e.g. 12 elements:
for e in x:
e.reverse()

Related

How can I check if a list of nodes have already been included in a list within a list of lists?

I have the following list: a = [[1,2,3],[4,5,6],[7,8,9]] which contains 3 lists, each being a list of nodes of a graph.
I am also given a tuple of nodes z = ([1,2], [4,9]). Now, I will like to check if either of the lists in z has been included in a list in a. For example, [1,2] is in [1,2,3], in a, but [4,9] is not in [4,5,6], although there is an overlapping node.
Remark: To clarify, I am also checking for sub-list of a list, or whether every item in a list is in another list. For example, I consider [1,3] to be "in" [1,2,3].
How can I do this? I tried implementing something similar found at Python 3 How to check if a value is already in a list in a list, but I have reached a mental deadlock..
Some insight on this issue will be great!
You can use any and all:
a = [[1,2,3],[4,5,6],[7,8,9]]
z = ([1,2], [4,9])
results = [i for i in z if any(all(c in b for c in i) for b in a)]
Output:
[[1, 2]]
You can use sets to compare if the nodes appear in a, <= operator for sets is equivalent to issubset().
itertools module provides some useful functions, itertools.product() is equivalent to nested for loops.
E.g.:
In []:
import itertools as it
[m for m, n in it.product(z, a) if set(m) <= set(n)]
Out[]:
[[1, 2]]
a = [[1,2,3],[4,5,6],[7,8,9]]
z = ([1,2], [4,9])
for z_ in z:
for a_ in a:
if set(z_).issubset(a_):
print(z_)
itertools.product is your friend (no installation builtin python module):
from itertools import product
print([i for i in z if any(tuple(i) in list(product(l,[len(i)])) for l in a)])
Output:
[[1, 2]]
Since you're only looking to test the sub-lists as if they were subsets, you can convert the sub-lists to sets and then use set.issubset() for the test:
s = map(set, a)
print([l for l in z for i in s if set(l).issubset(i)])
This outputs:
[[1, 2]]

How to subset an item:value list using another list with just items?

I have 2 lists. One is a list of words and their frequencies and the other is a list of words.
a = [('country',3478), ('island',2900),('river',5)]
b = ['river','mountain','bank']
There are thousands of entries in a but only hundreds in b.
How can I subset list a so that i return:
c=[('river',5)]
For loops would take too long given the number of entries and i imagine list comprehension is the solution but cannot get it right.
My main goal is to then create a wordcloud with my final list. Any help would be appreciated
**Edited because I made a mistake as pointed out by some commenters. I want to return
c=[('river',5)]
instead of
c=['river',5]
as i originally wrote. Apologies and thanks for pointing it out
I assume you actually want:
c = [('river',5)] # a list with one tuple
You better first construct a set of values in b:
bd = set(b)
then you can use list comprehension:
c = [(x,y) for x,y in a if x in bd]
That being said, if you want to lookup the frequency of a word, I advice you not to construct a list of tuples, but a dictionary. You can do this with dictionary comprehension:
c = {x: y for x,y in a if x in bd} # dictionary variant
You can try this:
a = [('country',3478), ('island',2900),('river',5)]
b = ['river','mountain','bank']
final_data = list([i for i in a if i[0] in b][0])
Output:
['river', 5]

Remove Variable(s) in List A if Variable(s) is/are in List B, Python

Like the title states I want to remove variables in one list if they happen to be in another list. I have tried various techniques but I can't seem to get a proper code. Can anyone help with this?
You may use list comprehension if you want to maintain the order:
>>> l = [1,2,3,4]
>>> l2 = [1,5,6,3]
>>> [x for x in l if x not in l2]
[2, 4]
In case the order of elements in original list don't matter, you may use set:
>>> list(set(l) - set(l2))
[2, 4]
def returnNewList(a,b):
h = {}
for e in b:
h[e] = True
return [e for e in a if e not in h]
hash table is used to keep the run time complexity linear.
In case list b is sorted then on place of using hash table you can perform binary search, complexity in this case will be nlog(n)
There are several ways
# just make a new list
[i for i in a if i not in b]
# use sets
list(set(a).difference(set(b)))
I figured it out, however is there a shorter way to write this code?
a = [0,1,2,3,4,5,6,7,8]
b = [0,5,8]
for i in a:
if i in b:
a.remove(i)

for loop in the range "first element of lists"

I have a list which has the following structure:
a = [[1,'a'], [2,'b'], [3,'c']]
I would like to create a range of the first element in every sub-list without making a second for-loop. I was thinking about something like this:
for i in a[][0]:
print i
However, the above last code does not work (SyntaxError: invalid syntax). Any idea if it's possible to do this in Python?
EDIT:
The output I would like to get with the above loop is:
1
2
3
and not
1
a
for sublist in a:
print sublist[0]
To build a list of first items, use list comprehension:
first_items = [sublist[0] for sublist in a]
for i,_ in a:
print i
should do the trick
This is probably overkill for such a simple example, but for variety:
for i in map(operator.itemgetter(0), a):
print i
In Python 2 map builds the whole list of first elements. You could use itertools.imap to avoid that. Of course for 3 elements it doesn't matter anyway.
I mention this because it's more flexible than for i, _ in a (there don't need to be exactly two elements in each sublist) and it gives you the i you want instead of doing for i in a and using i[0] (perhaps multiple times in a less simple example). But of course you could just as easily get the i you want with:
for l in a:
i = l[0]
print i
... not everything needs to be done in the loop header, it's just nice that it can be :-)
>>> a = [[1,'a'], [2,'b'], [3,'c']]
>>> for i in a:
... print i[0]
...
1
2
3
I think this method is kind of close to what you were trying.
>>> a = [[1,'a'], [2,'b'], [3,'c']]
>>> for [x,y] in a:
... print(x)
...
1
2
3
However,if your lists are of unequal size, then #warwaruk's answer is better.

list comprehension on multiple lists of lists

I am struck on an awkward lists comprehension problem, which I am not able to solve. So, I have two lists looking like the following:
a=[[....],[....],[....]]
b=[[....],[....],[....]]
len(a)==len(b) including sublists i.e sublists also have the same dimension.
Now I want to do a re.compile which looks something like:
[re.compile(_subelement_in_a).search(_subelement_in_b).group(1)]
and I am wondering how I can achieve the above using list compherension - something like:
[[re.compile(str(x)).search(str(y)).group(1) for x in a] for y in b]
..but obviously the above does not seem to work and I was wondering if anyone could point me in the right direction.
EDIT
I have just realized that the sublists of b have more elements than the sublists of a. So, for example:
a=[[1 items],[1 items],[1 items]]
b=[[10 item], [10 item], [10 item]]
I would still like to do the same as my above question:
[[re.compile(str(x)).search(str(y)).group(1) for x in b] for y in a]
and the output looking like:
c = [[b[0] in a[0] items],[b[1] in a[1] items],[b[2] in a[2] items]]
Example:
a=[["hgjkhukhkh"],["78hkugkgkug"],["ukkhukhylh"]]
b=[[r"""a(.*?)b""",r"""c(.*?)d""",r"""e(.*?)f""",r"""g(.*?)h""",r"""i(.*?)j"""],[r"""k(.*?)l""",r"""m(.*?)n""",r"""o(.*?)p""",r"""q(.*?)r"""],[r"""s(.*?)t""",r"""u(.*?)v""",r"""x(.*?)y""",r"""z(.*?)>"""]]
using one to one mapping. i.e check if:
elements of sublists of b[0] are present in sublist element of a[0]
elements of sublists of b[1] are present in sublist element of a[1]
elements of sublists of b[2] are presnet in sublist element of a[2]
Sounds like you are looking for zip? It takes a pair of lists and turns it into a list of pairs.
[
[my_operation(x,y) for x,y in zip(xs, ys)]
for xs, ys in zip(a, b)
]
-- Edit. Requirements changed:
[
[[regex(p, s) for p in patterns] for s in strings]
for strings, patterns in zip(a, b)
]
Use zip liberally:
[[re.search(x, y).group(1) for x,y in zip(s,t)] for s,t in zip(a,b)]
The first zip(a,b) produces lists of sublist pairs. The second zip pairs the elements in parallel sublists together.

Categories