How to change list of tuples to same tuples? [python] - python

I have list like this:
l = [("a"), ("b"), ("c")]
and i need to have:
l = ("a"), ("b"), ("c")
Someone know some reasonable quick way to do this?

You said you have a list of tuples. What you've shown isn't actually a list of tuples. It's a list of strings:
>>> [("a"), ("b"), ("c")]
['a', 'b', 'c']
>>> type(("a"))
<class 'str'>
I think what you meant was l = [("a",), ("b",), ("c",)]. That's a list of tuples.
To change your list of tuples into a tuple of tuples, you simply do:
>>> tuple(l)
(('a',), ('b',), ('c',))
EDIT - Note, that the following literal syntax:
l = ("a",), ("b",), ("c",)
Is a tuple of tuples.

You say you want
>>> want = ("a"), ("b"), ("c")
>>> want
('a', 'b', 'c')
You say you have
>>> have = [("a"), ("b"), ("c")]
>>> have
['a', 'b', 'c']
Use tuple() to get what you want from what you have:
>>> tuple(have)
('a', 'b', 'c')
>>> tuple(have) == want
True

If you want to make a list of strings to a tuple of strings simply use tuple()
>>> l = [("a"), ("b"), ("c")]
>>> l
['a', 'b', 'c']
>>>
>>> tuple(l)
('a', 'b', 'c')

Is this what you mean?
l = [(1,2),(2,3),(3,4)]
a,b,c = l
# now a = (1,2), b = (2,3), c = (3,4)
Otherwise the other answers should be able to help you. You might also want to look into the * operator ("unpacks" a list, so e.g. [*l,(4,5)] == [(1,2),(2,3),(3,4),(4,5)]) as well.
Either way, you might want to improve your phrasing for any other question you intend to post. Give concrete examples of what you want, what you tried and what (unintended) effects that had.

Related

how remove bracket from almost a nested list? [duplicate]

This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 1 year ago.
I have the following list:
my_list=[[['A','B'],'C'],[['S','A'],'Q']]
How I can remove the bracket from the first two elements?
output:
my_list=[['A','B','C'],['S','A','Q']]
Slice it in?
for a in my_list:
a[:1] = a[0]
This produces the desired output:
[x[0]+[x[1]] for x in my_list]
my_list=[
[['A','B'],'C'],
[['S','A'],'Q'],
]
result = [[item1, item2, item3] for (item1, item2), item3 in my_list]
>>> result
[['A', 'B', 'C'], ['S', 'A', 'Q']]
You can use the flattening solution in Cristian's answer on Flatten an irregular list of lists.
>>> [list(flatten(x)) for x in my_list]
[['A', 'B', 'C'], ['S', 'A', 'Q']]
Other people have already given the oneline solutions, but let's take a step back and think about how to approach this problem, so you can solve it for yourself.
The tools you need:
for [element] in list: Iterate over each element in a list
list[i]: Get the ith element of a list
list.append(element): Add an element to a list
Let's start with the simple case. We have [['A','B'],'C'] and want ['A','B','C'].
We want to
Get the sublist ['A', 'B']
Get the single item that isn't in the sublist, 'C'
Add the single item into the sublist
Make the sublist the main list
Sometimes it's easiest to sketch these things out in the python shell:
>>> l = [['A','B'],'C']
>>> l[0]
['A', 'B']
>>> l[1]
'C'
>>> l[0].append(l[1])
>>> l = l[0]
>>> l
['A', 'B', 'C']
Now, we can build up a function to do this
def fix_single_element(element):
"""
Given a list in the format [['A','B'],'C']
returns a list in the format ['A','B','C']
"""
# We use copy since we don't want to mess up the old list
internal_list = element[0].copy()
last_value = element[1]
internal_list.append(last_value)
return internal_list
Now we can use that:
>>> for sublist in my_list:
... print(sublist)
...
[['A', 'B'], 'C']
[['S', 'A'], 'Q']
Note that the sublists are exactly the problem we just solved.
>>> new_list = []
>>> for sublist in my_list:
... new_list.append(fix_single_element(sublist))
...
>>> new_list
[['A', 'B', 'C'], ['S', 'A', 'Q']]
There are LOTS of ways to do any particular task, and this is probably not the "best" way, but it's a way that will work. Focus on writing code you understand and can change, not the shortest code, especially when you start.

Merge elements in list of lists

I have a list of lists like this:
A = [('b', 'a', 'a', 'a', 'a'), ('b', 'a', 'a', 'a', 'a')]
How can I merge the all elements of each inner list to get result A = ['baaaa', 'baaaa']?
I would prefer to do this outside of a loop, if possible, to speed up the code.
If you don't want to write a loop you can use map and str.join
>>> list(map(''.join, A))
['baaaa', 'baaaa']
However, the loop using a list comprehension is almost as short to write, and I think is clearer:
>>> [''.join(e) for e in A]
['baaaa', 'baaaa']
You can use str.join:
>>> ["".join(t) for t in A]
['baaaa', 'baaaa']
>>>
>>>
>>> list(map(''.join, A) #with map
['baaaa', 'baaaa']
>>>
>>> help(str.join)
Help on method_descriptor:
join(...)
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
>>>
Use the join method of the empty string. This means: "make a string concatenating every element of a tuple (for example ('b', 'a', 'a', 'a', 'a') ) with '' (empty string) between each of them.
Thus, what you are looking for is:
[''.join(x) for x in A]
If you prefer functional programming. You can use the function reduce. Here is how you can achieve the same result using reduce function as follows.
Note that, reduce was a built in function in python 2.7 but in python
3 it is moved to library functools
from functools import reduce
It is only required to import reduce if you are using python 3 else no need to import reduce from functools
A = [('b', 'a', 'a', 'a', 'a'), ('b', 'a', 'a', 'a', 'a')]
result = [reduce(lambda a, b: a+b, i) for i in A]
If you don't want to use loop or even list comprehension, here is another way
list(map(lambda i: reduce(lambda a, b: a+b, i), A))

Access list elements that are not equal to a specific value

I am searching through a list like this:
my_list = [['a','b'],['b','c'],['a','x'],['f','r']]
and I want to see which elements come with 'a'. So first I have to find lists in which 'a' occurs. Then get access to the other element of the list. I do this by abs(pair.index('a')-1)
for pair in my_list:
if 'a' in pair:
print( pair[abs(pair.index('a')-1)] )
Is there any better pythonic way to do that?
Something like: pair.index(not 'a') maybe?
UPDATE:
Maybe it is good to point out that 'a' is not necessarily the first element.
in my case, ['a','a'] doesn't happen, but generally maybe it's good to choose a solution which handles this situation too
Are you looking for elements that accompany a? If so, a simple list comprehension will do:
In [110]: [x for x in my_list if 'a' in x]
Out[110]: [['a', 'b'], ['a', 'x']]
If you just want the elements and not the pairs, how about getting rid of a before printing:
In [112]: [(set(x) - {'a'}).pop() for x in my_list if 'a' in x]
Out[112]: ['b', 'x']
I use a set because a could either be the first or second element in the pair.
If I understand your question correctly, the following should work:
my_list = filter(
lambda e: 'a' not in e,
my_list
)
Note that in python 3, this returns a filter object instance. You may want to wrap the code in a list() command to get a list instance instead.
That technique works ok here, but it may be more efficient, and slightly more readable, to do it using sets. Here's one way to do that.
def paired_with(seq, ch):
chset = set(ch)
return [(set(pair) - chset).pop() for pair in seq if ch in pair]
my_list = [['a','b'], ['b','c'], ['x','a'], ['f','r']]
print(paired_with(my_list, 'a'))
output
['b', 'x']
If you want to do lots of tests on the same list, it would be more efficient to build a list of sets.
def paired_with(seq, ch):
chset = set(ch)
return [(pair - chset).pop() for pair in seq if ch in pair]
my_list = [['a','b'], ['b','c'], ['x','a'], ['f','r']]
my_sets = [set(u) for u in my_list]
print(my_sets)
print(paired_with(my_sets, 'a'))
output
[{'b', 'a'}, {'c', 'b'}, {'x', 'a'}, {'r', 'f'}]
['b', 'x']
This will fail if there's a pair like ['a', 'a'], but we can easily fix that:
def paired_with(seq, ch):
chset = set(ch)
return [(pair - chset or chset).pop() for pair in seq if ch in pair]
my_list = [['a','b'], ['b','c'], ['x','a'], ['f','r'], ['a', 'a']]
my_sets = [set(u) for u in my_list]
print(paired_with(my_sets, 'a'))
output
['b', 'x', 'a']

How to convert frozenset to normal sets or list?

For example, I have a frozen set
[frozenset({'a', 'c,'}), frozenset({'h,', 'a,'})]
I want to convert it to a normal list like
[['a', 'c,'],['a,', 'd,']...]
What method should I use?
sets=[frozenset({'a', 'c,'}), frozenset({'h,', 'a,'})]
print([list(x) for x in sets])
The list comprehension will convert every frozenset in your list of sets and put them into a new list. That's probably what you want.
You can also you map, map(list, sets). Please be aware, that in Python 3, if you want the result of map as list you need to manually convert it using list, otherwise, it's just a map object which looks like <map object 0xblahblah>
We can convert frozenset object x to list or set by using list() or set() on it. So we can do this on each item in the list containing frozensets as mentioned in the another by Ivan
>>> x=frozenset(['a','b','c','d'])
>>> print(x)
frozenset({'c', 'd', 'a', 'b'})
>>> y=list(x)
>>> y
['c', 'd', 'a', 'b']
>>> y = set(x)
>>> y
{'c', 'd', 'a', 'b'}

How do you find common sublists between two lists? [duplicate]

This question already has answers here:
Finding intersection/difference between python lists
(7 answers)
Closed 9 years ago.
How do you find or keep only the sublists of a list if it the sublist is also present within another list?
lsta = [['a','b','c'],['c','d','e'],['e','f','g']]
lstb = [['a','b','c'],['d','d','e'],['e','f','g']]
I'd like to do something like set(lsta) & set(lstb)
Desired_List = [['a','b','c'],['e','f','g']]
The reason I'd like to do something like set is for it's speed as I'm doing this on a very large list where efficiency is quite important.
Also, slightly unrelated, what if I wanted to subtract lstb from lsta to get
Desired_List2 = [['d','d','e']]
Better change the list of lists to list of tuples, then you can easily use the set operations:
>>> tupa = map(tuple, lsta)
>>> tupb = map(tuple, lstb)
>>> set(tupa).intersection(tupb)
set([('a', 'b', 'c'), ('e', 'f', 'g')])
>>> set(tupa).difference(tupb)
set([('c', 'd', 'e')])
If your sub-lists need to remain lists, use a list comprehension
Intersection:
>>> [i for i in lsta if i in lstb]
[['a', 'b', 'c'], ['e', 'f', 'g']]
Subtraction:
>>> [i for i in lsta if i not in lstb]
[['c', 'd', 'e']]
I have written a C module a while ago for this:
>>> lsta = [['a','b','c'],['c','d','e'],['e','f','g']]
>>> lstb = [['a','b','c'],['d','d','e'],['e','f','g']]
>>> list(boolmerge.andmerge(lsta, lstb))
>>> import boolmerge
[['a', 'b', 'c'], ['e', 'f', 'g']]
This is O(n) time, and require the lists to be sorted.

Categories