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

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(", "))

Related

How to use trim strings in a list comprehension? [duplicate]

This question already has answers here:
Strip a list in Python [closed]
(3 answers)
Closed 5 months ago.
keywords = ['a', 'b', '(c)']
keywords = [keyword for keyword in keywords if "(" in keyword and ")" in keyword]
I want the output to be:
keywords = ['a', 'b', 'c']
How to modify the list comprehension to get the result without using a loop?
Try strip:
>>> keywords = ['a', 'b', '(c)']
>>> [kw.strip('()') for kw in keywords]
['a', 'b', 'c']
>>>
strip works. Alternate solution using replace() as well:
>>> keywords = ['a', 'b', '(c)']
>>> [kw.replace('(','').replace(')','') for kw in keywords]
['a', 'b', 'c']
A list comprehensions in Python is a type of loop
Without using a loop:
keywords = ['a', 'b', '(c)']
keywords = list(map(lambda keyword: keyword.strip('()'), keywords))

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

Generating a list of random lists

I'm new to Python, so I might be doing basic errors, so apologies first.
Here is the kind of result I'm trying to obtain :
foo = [
["B","C","E","A","D"],
["E","B","A","C","D"],
["D","B","A","E","C"],
["C","D","E","B","A"]
]
So basically, a list of lists of randomly permutated letters without repeat.
Here is the look of what I can get so far :
foo = ['BDCEA', 'BDCEA', 'BDCEA', 'BDCEA']
The main problem being that everytime is the same permutation. This is my code so far :
import random
import numpy as np
letters = ["A", "B", "C", "D", "E"]
nblines = 4
foo = np.repeat(''.join(random.sample(letters, len(letters))), nblines)
Help appreciated. Thanks
The problem with your code is that the line
foo = np.repeat(''.join(random.sample(letters, len(letters))), nblines)
will first create a random permutation, and then repeat that same permutation nblines times. Numpy.repeat does not repeatedly invoke a function, it repeats elements of an already existing array, which you created with random.sample.
Another thing is that numpy is designed to work with numbers, not strings. Here is a short code snippet (without using numpy) to obtain your desired result:
[random.sample(letters,len(letters)) for i in range(nblines)]
Result: similar to this:
foo = [
["B","C","E","A","D"],
["E","B","A","C","D"],
["D","B","A","E","C"],
["C","D","E","B","A"]
]
I hope this helped ;)
PS: I see that others gave similar answers to this while I was writing it.
np.repeat repeats the same array. Your approach would work if you changed it to:
[''.join(random.sample(letters, len(letters))) for _ in range(nblines)]
Out: ['EBCAD', 'BCEAD', 'EBDCA', 'DBACE']
This is a short way of writing this:
foo = []
for _ in range(nblines):
foo.append(''.join(random.sample(letters, len(letters))))
foo
Out: ['DBACE', 'CBAED', 'ACDEB', 'ADBCE']
Here's a plain Python solution using a "traditional" style for loop.
from random import shuffle
nblines = 4
letters = list("ABCDE")
foo = []
for _ in range(nblines):
shuffle(letters)
foo.append(letters[:])
print(foo)
typical output
[['E', 'C', 'D', 'A', 'B'], ['A', 'B', 'D', 'C', 'E'], ['A', 'C', 'B', 'E', 'D'], ['C', 'A', 'E', 'B', 'D']]
The random.shuffle function shuffles the list in-place. We append a copy of the list to foo using letters[:], otherwise foo would just end up containing 4 references to the one list object.
Here's a slightly more advanced version, using a generator function to handle the shuffling. Each time we call next(sh) it shuffles the lst list stored in the generator and returns a copy of it. So we can call next(sh) in a list comprehension to build the list, which is a little neater than using a traditional for loop. Also, list comprehesions can be slightly faster than using .append in a traditional for loop.
from random import shuffle
def shuffler(seq):
lst = list(seq)
while True:
shuffle(lst)
yield lst[:]
sh = shuffler('ABCDE')
foo = [next(sh) for _ in range(10)]
for row in foo:
print(row)
typical output
['C', 'B', 'A', 'E', 'D']
['C', 'A', 'E', 'B', 'D']
['D', 'B', 'C', 'A', 'E']
['E', 'D', 'A', 'B', 'C']
['B', 'A', 'E', 'C', 'D']
['B', 'D', 'C', 'E', 'A']
['A', 'B', 'C', 'E', 'D']
['D', 'C', 'A', 'B', 'E']
['D', 'C', 'B', 'E', 'A']
['E', 'D', 'A', 'C', 'B']

Create new lists with del function

I have a list
a = ['a', 'b', 'c']
And I want to create a function Delete where it would print to a new list the lists['a', 'b'], ['b', 'c'] and ['a', 'c'].
My main goal here is designing a function that would return a set of lists consisting of the main list without an element of it.
What you want is all combinations of length n-1 where n is the length of your list.
>>> from itertools import combinations
>>> a = ['a', 'b', 'c']
>>> map(list, combinations(a, len(a)-1))
[['a', 'b'], ['a', 'c'], ['b', 'c']]
This will give you a list of lists.
Note that a set of lists which you requested is not possible because lists are not hashable.

Categories

Resources