Avoid for loop? [duplicate] - python

This question already has answers here:
Python -Intersection of multiple lists?
(6 answers)
Closed 3 years ago.
Is there a way to avoid this for loop in favor of efficiency? I was thinking about iter/next functions but they don't seem to work properly..
def foo():
lst = [['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['d', 'h', 'i', 'j']]
res = set(lst[0])
for word in lst:
res = res.intersection(word)
return ''.join(res)

set.intersection isn't limited to a single argument.
res = set(lst[0]).intersection(*lst[1:])
For example:
>>> foo = set([1,2,3])
>>> foo.intersection([1,2])
{1,2}
>>> foo.intersection([2,3])
{2,3}
>>> foo.intersection([1,2], [2,3])
{3}

Related

how to create a list from multiple sublists [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 6 months ago.
I have a list with the following structure:
list = ['a', ['b','c','d'], ['e','f']]
how can I create the following structure from it:
list = ['a','b','c','d','e','f']
list = ['a', ['b','c','d'], ['e','f']]
lst = [element for nested_list in list for element in nested_list]
print(lst)
Result:
['a', 'b', 'c', 'd', 'e', 'f']
This supports nested list too.
res = []
def parse(li):
if isinstance(li, list):
for a in li:
parse(a)
return
res.append(li)
my_List = ['a', ['b','c','d', ['g', 'h']], ['e','f']]
parse(my_List)
print(res)
Output:
['a', 'b', 'c', 'd', 'g', 'h', 'e', 'f']

How do you find duplicate strings in a list? [duplicate]

This question already has answers here:
How do I find the duplicates in a list and create another list with them?
(42 answers)
Closed 3 years ago.
I have a list with several stings, with some being duplicates. I need to pull out all the duplicate strings and append them into a new list. How can I do that?
list_i = ['a','b','a','c','a','c','g','w','s','c','d','a','b','c','a','e']
Use an OrderedDict to get a list without the duplicates then remove those from a copy of the original
from collections import OrderedDict
list_i = ['a','b','a','c','a','c','g','w','s','c','d','a','b','c','a','e']
non_dupes = list(OrderedDict.fromkeys(list_i))
dupes = list(list_i)
for d in non_dupes:
dupes.remove(d)
print(dupes)
#['a', 'a', 'c', 'c', 'a', 'b', 'c', 'a']
print(non_dupes)
#['a', 'b', 'c', 'g', 'w', 's', 'd', 'e']

How to dynamically unpack a list as you create? [duplicate]

This question already has answers here:
Unpack list into middle of a tuple
(3 answers)
Closed 4 years ago.
How would I create a list element from function call?
Not sure if this is possible, but I've tried to create a list element from a function when i create the list as i'm not sure of the elements up until runtime
So I have tried this:
>>>> def make_list_element():
return 'd, e'
If i then try to create a list and call the function at the same time :
>>>> a = ['a', 'b', 'c', make_list_element().split(", ")]
And I get:
>>> a
>>> ['a', 'b', 'c', ['d', 'e']]
How could I achieve this:
>>> a
>>> ['a', 'b', 'c', 'd', 'e']
Preferably in the same statement as I create the list.
Many thanks
In Python3, you can simply unpack the returned list like so:
a = ['a', 'b', 'c', *make_list_element().split(", ") ]
If you're on Python2, you will have to concatenate or extend the list:
a = ['a', 'b', 'c'] + make_list_element().split(", ")
or
a = ['a', 'b', 'c']
a.extend(make_list_element().split(", "))

Convert a list of list's names(str) into a list of lists in python [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I am new to python and I have search a lot about this issue. I know there is a way of converting tuples to a list, but somehow it doesn't work for me. Here is my issue.
Say I have:
l_1 = ['a','b','c']
l_2 = ['e','f','g']
l_3 = ['g','h','i']
Then say I have another list of:
l_all = ['l_1','l_2','l_3']
How can I convert it(l_all) to a list of
[['a','b','c'],['e','f','g'],['g','h','i']]
I tried ast package using ast.literal_eval, but I received this error:
ValueError: malformed node or string: <_ast.Name object at
0x00000172CA3C5278>
I also tried to use json package, still no luck.
I tried just output ast.literal_eval('l_1'), not working either.
I'd really appreciate if anyone can help on this.
Thanks a lot!
That sounds like a problem that should be fixed upstream
ast.literal_eval evaluates literals. eval is just 1) cheating and 2) so dangerous I wouldn't recommend it at all.
Anyway, you could scan global then local variables using global & local dicts in a list comprehension:
l_1 = ['a','b','c']
l_2 = ['e','f','g']
l_3 = ['g','h','i']
l_all = ['l_1','l_2','l_3']
l_all = [globals().get(x,locals().get(x)) for x in l_all]
result:
[['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']]
globals().get(x,locals().get(x)) is a quick & dirty code to first look in global vars & fallback to local vars if not found. It could be overcomplicated for your needs.
You can use a dictionary to store the list names and each associated list:
d = {'l_2': ['e', 'f', 'g'], 'l_3': ['g', 'h', 'i'], 'l_1': ['a', 'b', 'c']}
l_all = ['l_1','l_2','l_3']
final_results = [d[i] for i in l_all]
Output:
[['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']]
However, to actually access the lists via variable name, you would have to use globals:
l_1 = ['a','b','c']
l_2 = ['e','f','g']
l_3 = ['g','h','i']
l_all = ['l_1','l_2','l_3']
new_l = [globals()[i] for i in l_all]
Output:
[['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']]
You can simply do:
l_1 = ['a','b','c']
l_2 = ['e','f','g']
l_3 = ['g','h','i']
l_all = ['l_1','l_2','l_3']
print(list(map(lambda x:globals()[x],l_all)))
output:
[['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']]
Then say I have another list of:
l_all = ['l_1','l_2','l_3']
Let's say you don't create this using strings, and use the list variables directly
You can then get the wanted output
l_all = [l_1,l_2, l_3]
You can use locals()
l_1 = ['a','b','c']
l_2 = ['e','f','g']
l_3 = ['g','h','i']
l_all = ['l_1', 'l_2', 'l_3']
all_local_variables = locals()
l_all_values = [all_local_variables[i] for i in l_all]
And you should be aware that you can get KeyError if no such variable present in current scope, for that you can all_local_variables.get(i), that will return None if not present or set default as all_local_variables.get(i, 'default')
The simplest way to do this is to evaluate your strings in l_all. Something like this
>>> l_1 = ['a','b','c']
>>> l_2 = ['e','f','g']
>>> l_3 = ['g','h','i']
>>> l_all = ['l_1','l_2','l_3']
>>> [ eval(x) for x in l_all ]
The output is
[['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']]

Python list in list [duplicate]

This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 10 years ago.
I want convert list as follow:
list=[['a','b','c','d'],'e','f']
to
list['a','b','c','d','e','f']
how could I do this....Helples..
Check out itertools.chain, I think it's exactly what you need: http://docs.python.org/2/library/itertools.html#itertools.chain
>>> import itertools as it
>>> li = [['e', 'f', 'g'], 'a', 'b']
>>> list(it.chain.from_iterable(li))
['e', 'f', 'g', 'a', 'b']
This is pretty much the example from the documentation of that function, which is always a good place to start...

Categories

Resources