This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 3 years ago.
I'm trying to remove some specific '' in the list using python.
The list is [1,'','',2,'','','',3,'']. I want to remove just one '' between two values. which means the output I want is [1,'',2,'','',3]. The code I had shows as below:
for j in range (len(lst)):
if len(lst[j]) == 1:
lst.remove(lst[j+1])
Using itertools.groupby:
from itertools import groupby
l = [1,'','',2,'','','',3,'']
new_list = []
for v, g in groupby(l):
new_list += list(g) if v != '' else list(g)[:-1]
print(new_list)
Prints:
[1, '', 2, '', '', 3]
Version 2 (one-liner with itertools.chain):
from itertools import groupby, chain
l = [1,'','',2,'','','',3,'']
new_list = [*chain.from_iterable(list(g) if v != '' else list(g)[:-1] for v, g in groupby(l))]
print(new_list)
You can use the del operator. Just provide the index. del lst[1].
Related
This question already has answers here:
if/else in a list comprehension
(12 answers)
Closed 1 year ago.
I have a list of strings
str_list = ['a', 'b', 'c']
and want to add a suffix
suffix = '_ok'
when the string value is 'a'.
This works:
new_str_list = []
for i in str_list:
if i == 'a':
new_str_list.append(i + suffix)
else:
new_str_list.append(i)
new_str_list
# ['a_ok', 'b', 'c']
How can I simplify this with a list comprehension?
Something like
new_str_list = [i + suffix for i in str_list if i=='a' ....
[i + suffix if i == 'a' else i for i in str_list]
Putting if after the for as you tried is for skiping values.
In your case you don't skip values but process them differently.
Create the item according to it's value -
[i + suffix if i=='a' else i for i in str_list ]
A concise option making use of fact that False == 0:
[i + suffix * (i=='a') for i in str_list]
This question already has answers here:
Removing duplicate characters from a string
(15 answers)
Closed 2 years ago.
I have a list l = ['AAB', 'CAA', 'ADA'] . I want to get the following list without duplicated characters new_l = ['AB','CA','AD']. I am trying to iterate on a nested loop but I'm not sure this is the best way to accomplish this. here is my try:
new_l = []
for i in range(0,len(l)-1):
for j in range(0,len(l)-1):
if l[i][j] != l[i+1][j+1]:
new_l = ..............
Can someone help me on how to get a set by iterating over every element of this list of strings ?
You can easily do it, since a string is also a list.
strl = ['AAB', 'CAA', 'ADA']
new_strl = []
for s in strl:
new_strl.append("".join(set(s)))
print(new_strl)
Set can mess order of characters. Better use OrderedDict:
from collections import OrderedDict
strl = ['AAB', 'CAA', 'ADA']
result = ["".join(OrderedDict.fromkeys(s)) for s in strl]
l = ['AAB', 'CAA', 'ADA']
new_l = [''.join(sorted(set(x))) for x in l]
#op
['AB', 'AC', 'AD']
This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 3 years ago.
I am new to python and am trying to create a new list from 2 other lists by appending each item in the list.
for number in num:
for names in name:
print(number+names)
num = [1,2,3,4,5]
name = ['Tom','Bob','Dave']
new_desired_list = [1Tom,1Bob,1Dave,2Tom,2Bob,2Data,3Tom,3Bob,3Dave..etc]
Seems like you want the cartesian product of both lists. For that you have itertools.product. In order to join the strings you could use string formatting:
from itertools import product
[f'{i}{j}' for i,j in product(num, name)]
# ['{}{}'.format(i,j) for i,j in product(num, name)] # for Python 3.6<
# ['1Tom', '1Bob', '1Dave', '2Tom', '2Bob'...
You could try appending a list ;)
l = []
numbers = [1,2,3,4,5]
names = ['Tom','Bob','Dave']
for number in numbers:
for name in names:
l.append(str(number) + str(name))
print(l)
Use list comprehension:
new_list = [str(i)+x for i in num for x in name]
Example:
>>> num = [1,2,3,4,5]
>>> name = ['Tom','Bob','Dave']
>>>
>>> new_list = [str(i)+x for i in num for x in name]
>>> new_list
['1Tom', '1Bob', '1Dave', '2Tom', '2Bob', '2Dave', '3Tom', '3Bob', '3Dave', '4Tom', '4Bob', '4Dave', '5Tom', '5Bob', '5Dave']
>>>
This question already has answers here:
Is there a zip-like function that pads to longest length?
(8 answers)
Closed 3 years ago.
I know a way to interleave two strings using Python but it works only if their lengths are equal:
u = 'Abcd'
l = 'Wxyz'
res = "".join(i + j for i, j in zip(u, l))
print(res)
This will give me the correct Output:AWbxcydz
But if the strings are u = 'Utkarsh' and l = 'Jain', the same method does not give the correct answer. Can someone suggest a way to do so?
Use zip_longest from itertools.
from itertools import zip_longest
u = 'Abcdefgh'
l = 'Wxyz'
res = "".join(i + j for i, j in zip_longest(u, l, fillvalue=''))
print(res)
This question already has answers here:
Split by comma and strip whitespace in Python
(10 answers)
Closed 4 years ago.
Input list example = ['listen, silent', 'dog, fog', 'colour, simple']
how do I return a nested list from the example in pairs, to look like this:
[[word1,word2], [word3,word4]...etc]
please, thank you
I have tried list comprehension,
my_list1 = [i[1] for i in my_list]
my_list2 = [i[0] for i in my_list]
but it took out only the first letter instead of word... hoping for it to look like;
[listen, silent],[dog, fog]...etc
You can split each word in the list using , as a separator:
l = ['listen, silent', 'dog, fog', 'colour, simple']
l = [elem.split(', ') for elem in l]
print(l)
Output:
[['listen', 'silent'], ['dog', 'fog'], ['colour', 'simple']]