List comprehension: Multiply each string to a single list - python

I have a list of strings and want to get a new list consisting on each element a number of times.
lst = ['abc', '123']
n = 3
I can do that with a for loop:
res = []
for i in lst:
res = res + [i]*n
print( res )
['abc', 'abc', 'abc', '123', '123', '123']
How do I do it with list comprehension?
My best try so far:
[ [i]*n for i in ['abc', '123'] ]
[['abc', 'abc', 'abc'], ['123', '123', '123']]

Use a nested list comprehension
>>> lst = ['abc', '123']
>>> n = 3
>>> [i for i in lst for j in range(n)]
['abc', 'abc', 'abc', '123', '123', '123']
The idea behind this is, you loop through the list twice and you print each of the element thrice.
See What does "list comprehension" mean? How does it work and how can I use it?

It can also be done as:
>>> lst = ['abc', '123']
>>> n=3
>>> [j for i in lst for j in (i,)*n]
['abc', 'abc', 'abc', '123', '123', '123']

Related

Add list items of one list to another list of list at same index

How can I achieve the below result? Both the list have same index size.
list_1 = [ 'arn1', 'arn2' ]
list_2 =[
['abc', '123'],
['pqr' , '789']
]
expected_output = [
['abc', '123', 'arn1'],
['pqr' , '789', 'arn2']
]
When trying to combine two lists item by item, zip is something you should always start with.
zip(list_1, list_2)
In this case, what you want is:
[ys + [x] for x, ys in zip(list_1, list_2)]
Which gives:
[['abc', '123', 'arn1'], ['pqr', '789', 'arn2']]
You can just use enumerate to loop to the first list, get the index then append to the second list.
list_1 = [ 'arn1', 'arn2' ]
list_2 =[
['abc', '123'],
['pqr' , '789']
]
for i, item in enumerate(list_1):
list_2[i].append(item)
print(list_2)
A slightly longer solution, but simpler:
list_1 = ['arn1', 'arn2']
list_2 = [['abc', '123'], ['pqr', '789']]
expected_output = [['abc', '123', 'arn1'], ['pqr', '789', 'arn2']]
output = []
for i in range(0, len(list_1)): # iterates
added_list = list_2[i] + [list_1[i]]
output.append(added_list)
print(output == expected_output)
# True
Or a list comprehension, if you want one:
output_list_comprehension = [list_2[i] + [list_1[i]] for i in range(0, len(list_1))]
#returns same answer

Is there a way to make a nested loop with as many loops as you like (python)? [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 3 years ago.
The thing i'm trying to do is to create every single combination, but only using one of each letter
I did it with 3 sets of letters
inlist = ["Aa", "Bb", "Cc"]
outlist = []
for i in inlist[0]:
for j in inlist[1]:
for k in inlist[2]:
outlist.append(str(i + j + k))
Output:
outlist = ['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']
What if i want to do this with 2 or 4 sets of letters? Is there an easier way?
itertools.product does exactly that:
from itertools import product
inlist = ["Aa", "Bb", "Cc"]
outlist = []
for abc in product(*inlist):
outlist.append(''.join(abc))
print(outlist)
# ['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']
abc is a tuple going from ('A', 'B', 'C') to ('a', 'b', 'c'). the only thing left to to is join that back to a string with ''.join(abc).
>>> import itertools
>>> inlist = ["Aa", "Bb", "Cc"]
>>> [''.join(i) for i in itertools.product(*inlist)]
['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']

grouping a list into sublists, breaked by alphabet elements in python

I have a list in python that is mixed: some elements are numeric and some are alphabet.
For example: l = ['999','123','hello','222','333','444','bye']
I want to split this list to a lists that are seperated by the elements that are all alphabet:
['999','123','hello'], ['222','333','444','bye']
For ['hello', '123', 'test', 'test', '456', 'test', '789']
The output will be: ['hello'],['123','test'],['test'],['456','test'],['789']
Every element is all alphabet or all numeric.
What is the most pythonic way to do so?
output = []
for i in l:
if not output or output[-1][-1].isalpha():
output.append([i])
else:
output[-1].append(i)
so that with:
l = ['999','123','hello','222','333','444','bye']
output would become:
[['999', '123', 'hello'], ['222', '333', '444', 'bye']]
or with:
l = ['hello', '123', 'test', 'test', '456', 'test', '789']
output would become:
[['hello'], ['123', 'test'], ['test'], ['456', 'test'], ['789']]

How can I remove a specific number from a string?

here is the code:
aList = ['0.01', 'xyz', 'J0.01', 'abc', 'xyz'];
aList.remove('0.01');
print("List : ", aList)
here is the output:
List :
['xyz', 'J0.01', 'abc', 'xyz']
How can I remove the 0.01 attached to 'J0.01'? I would like to keep the J. Thanks for your time! =)
Seems like you want
aList = ['0.01', 'xyz', 'J0.01', 'abc', 'xyz'];
>>> [z.replace('0.01', '') for z in aList]
['', 'xyz', 'J', 'abc', 'xyz']
If you want to remove also empty strings/whitespaces,
>>> [z.replace('0.01', '') for z in aList if z.replace('0.01', '').strip()]
['xyz', 'J', 'abc', 'xyz']
Using re module:
import re
aList = ['0.01', 'xyz', 'J0.01', 'abc', 'xyz'];
print([i for i in (re.sub(r'\d+\.?\d*$', '', i) for i in aList) if i])
Prints:
['xyz', 'J', 'abc', 'xyz']
EDIT:
The regexp substitution re.sub(r'\d+\.?\d*$', '', i) will substitute every digit followed by dot (optional) and followed by any number of digits for empty string. The $ signifies that the digit should be at the end of the string.
So. e.g. the following matches are valid: "0.01", "0.", "0". Explanation on external site here.
Something like that can works:
l = ['0.01', 'xyz', 'J0.01', 'abc', 'xyz']
string = '0.01'
result = []
for x in l :
if string in x:
substring = x.replace(string,'')
if substring != "":
result.append(substring)
else:
result.append(x)
print(result)
try it, regards.

How to check if list1 contains some elements of list2?

I need to remove few strings from the list1 so i put them into list2 and just cant find out how to make it works.
list1 = ['abc', 'def', '123']
list2 = ['def', 'xyz', 'abc'] # stuff to delete from list1
And I would like to remove 'abc' and 'def' from list1 so it only contains things that i need
You can do this by using list comprehension as a filter, like this
set2, list1 = set(['def', 'xyz', 'abc']), ['abc', 'def', '123']
print [item for item in list1 if item not in set2]
# ['123']
We convert the elements of list2 to a set, because they offer faster lookups.
The logic is similar to writing like this
result = []
for item in list1:
if item not in set2:
result.append(item)
If you don't have any duplicate in list1 (or if you want to remove duplicates), you can use this:
list1 = set(['abc', 'def', '123'])
list2 = set(['def', 'xyz', 'abc'])
print(list(list1 - list2))
list1 = set(['abc', 'def', '123'])
list2 = set(['def', 'xyz', 'abc'])
# here result will contain only the intersected element
# so its very less.
result = set(filter(set(list1).__contains__, list2))
newlist = list()
for elm in list1:
if elm not in result:
newlist.append(elm)
print newlist
Output:
['123']
An even shorter answer using builtin set methods:
list1 = ['abc', 'def', '123']
list2 = ['def', 'xyz', 'abc']
set1 = set(list1)
set2 = set(list2)
print(set1.difference(set2)))
Quote from above documentation:
"Return a new set with elements in the set that are not in the others."

Categories

Resources