Removing neighboring duplicates in list in python [duplicate] - python

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.

Related

Python list comprehension with multiple conditions [duplicate]

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]

removing duplicates by comparing substrings in a list [duplicate]

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

Remove specific item in a list [duplicate]

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

How to Interleave two strings in Python when their lengths are not equal? [duplicate]

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)

How do i make this list into a string in python? [duplicate]

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)

Categories

Resources