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]
Related
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 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].
This question already has answers here:
How to remove duplicates only if consecutive in a string? [duplicate]
(9 answers)
Closed 4 years ago.
I convert string a to a list and I want the loop to create tabb = ['a', 'b', 'c', 'a']
a = aaabbbbcccaaa
taba = list(a)
tabb = []
for i in taba:
for j in range(len(tabb)):
if not i[j] == i[j-1]:
tabb.append(i[j])
print (tabb)
But apparently my solution gives tabb = []
Do You have any better and simple ideas to make it work?
groupby from itertools is your ally:
from itertools import groupby
a = 'aaabbbbcccaaa'
res = [x for x, _ in groupby(a)]
print(res) # -> ['a', 'b', 'c', 'a']
The solution without any libraries (the one you were trying to arrive at) would be:
res = [a[0]]
for i, c in enumerate(a[1:]):
if c != a[i]:
res.append(c)
which has the same outcome of course.
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 6 years ago.
For example, suppose we have a string:
'abcdefg'
And we need to get a list like this:
['ab', 'bc', 'cd', 'de', 'ef', 'fg']
we should not use any kind of library
Here is my solution:
def str_split(s):
s = iter(s)
ch1=''
ch2=''
chars_list=[]
while True:
try:
ch1 = ch2 or next(s)
ch2 = next(s)
chars_list.append(ch1 + ch2)
except:
break
return chars_list
I wonder is there a better solution? Maybe it is possible to use list comprehension like here?
You can simply use zip() and a list comprehension:
chars_list = [ch1 + ch2 for ch1, ch2 in zip(s, s[1:])]
More generally, if you need a solution for any n:
n = 3
chars_list = [s[i:i+n] for i in range(0, len(s) - n + 1, n - 1)]
# ['abc', 'cde', 'efg']
You could try this (hacky) solution:
def str_split(s):
return [s[start:end] for start, end in enumerate(range(2, len(s)+1))]
Delgan's zipping solution seems more elegant though :)
This question already has answers here:
Converting a list to a string [duplicate]
(8 answers)
How to convert list to string [duplicate]
(3 answers)
Closed 9 years ago.
I am trying, in the following code, to encrypt a message. The problem is that my result comes up in a list format instead of a string. How do I make it into a string?
You need to flatten the nested lists in your result and then turn it into a string. Here's one way to do it:
>>> import itertools
>>> result = [['I', 'R', 'A', ' ', 'O'], [' ', 'E', 'D', 'Y', 'U']]
>>> ''.join(itertools.chain(*result))
'IRA O EDYU'
finalArray is clearly a list:
finalArray = []
To convert it to a string, use join:
print ''.join(finalArray)
But first, you probably do not want these nested lists. You should use extend, not append:
def stringEncrypter(A):
length = len(A)
finalArray = []
if length%2 == 0:
firstArray=[]*(length/2)
secondArray=[]*(length/2)
else:
firstArray=[]*((length+1)/2)
secondArray=[]*((length-1)/2)
for x in range(0, length-1):
if x%2 == 0:
firstArray.append(A[x:x+1])
secondArray.append(A[x+1:x+2])
finalArray.extend(firstArray)
finalArray.extend(secondArray)
print ''.join(finalArray)