How to combine two elements of a list based on a given condition
This does not create a new list, just modifies the existing one.
l = ['a', 'b', 'c', 'a', 'd']
for i in range(len(l)-2, -1, -1):
if l[i] == 'a':
l[i] = l[i] + l.pop(i+1)
print(l)
Merging items in list given condition
A simple algorithm solving this appears to be:
- initialize results as empty list
- repeat for each pair in input list:
- repeat for each sublist R in results:
- if R contains the first item of pair, append second item to R and continue with next pair
- if no sublist R contained the first item of pair, append pair as new sublist to results
- repeat for each sublist R in results:
The implementation in Python is straightforward and should be self-explanatory:
def merge_pairs(pairs):
results = []
for pair in pairs:
first, second = pair.split()
for result in results:
if first in result:
result.append(second)
break
else:
results.append([first, second])
return [' '.join(result) for result in results]
The only extra steps are the conversions between space-separated letters and lists of letters by .split()
and ' '.join()
.
Note the else
clause of the for
statement which is only executed if no break
was encountered.
Some examples:
>>> merge_pairs(['A B', 'B C', 'X Y', 'C D', 'Y Z', 'D E', 'C G'])
['A B C D E G', 'X Y Z']
>>> merge_pairs(['A B', 'A C'])
['A B C']
>>> merge_pairs(['B C', 'A B'])
['B C', 'A B']
How to merge elements in list in python with condition?
This will work:
[list_i[i] + ":" + list_i[i+1] for i in range(0, len(list_i), 2)]
This produces:
['teacher:10', 'student:100', 'principle:2']
efficient way to merge consecutive list elements based on condition
orig_list = [
(287, 790),
(855, 945),
(955, 2205),
(2230, 2264),
(2362, 2729),
(3906, 4473)]
merged_list = []
# iterate through original list
orig_iter = iter(orig_list)
# pop the first element and keep track of it as the "last tuple visited"
last_tuple = next(orig_iter)
for next_tuple in orig_iter:
# if tuples are too close, merge them
if (next_tuple[0] - last_tuple[1]) < 100:
last_tuple = (last_tuple[0], next_tuple[1])
# otherwise, push the last_tuple to the new list and replace it
else:
merged_list.append(last_tuple)
last_tuple = next_tuple
# when we're done traversing the list, push whatever's remaining onto the end
merged_list.append(last_tuple)
print(merged_list)
# [(287, 2729), (3906, 4473)]
Note that (287, 2205)
merges with (2230, 2264)
since the difference is less than 100. I suspect this was a typo in the original question.
Combine elements of lists if some condition
Use itertools.groupby
:
>>> from itertools import groupby
>>> out = []
>>> for lst in words:
d = []
for k, g in groupby(lst, lambda x: '!' in x):
if k:
d.append(', '.join(g))
else:
d.extend(g)
out.append(d)
...
>>> out
[['this', 'that!', 'riff', 'raff'],
['hip', 'hop!, flip!', 'flop'],
['humpty', 'dumpty!, professor!, grumpy!']]
Merge list items based on condition within the list
Using a generator.
def merge(x, key='IP'):
tmp = []
for i in x:
if (i[0:len(key)] == key) and len(tmp):
yield ' '.join(tmp)
tmp = []
tmp.append(i)
if len(tmp):
yield ' '.join(tmp)
a = ['IP 123 84','apple','mercury','IP 543 65','killer','parser','goat','IP 549 54 pineapple','django','python']
print list(merge(a))
['IP 123 84 apple mercury', 'IP 543 65 killer parser goat', 'IP 549 54 pineapple django python']
How to combine Python list elements on either side of i when i mets a certain condition
The best is to use the re
module
import re
mylist = ["<s1", "a","b","<s16", "<s18", "c", "d", "e", "f", "<s16", "g", "h", "i", "j", "<s135"]
# So you will catch strings which starts with "<s" followed by some digits
# and after zero or more entries of any caracter.
r = "^<s\d+.*"
i = 0
while i < len(mylist):
item = mylist[i]
# If you are at the start of the list just pop the first item
if (i == 0) and re.search(r, item):
mylist.pop(i)
# If you are at the end of the list just pop the last item
elif (i == len(mylist) - 1) and re.search(r, item):
mylist.pop(i)
# If you have found a wrong item inside the list
# continue until you delete all consecutive entries
elif re.search(r, item):
mylist.pop(i)
item = mylist[i]
while re.search(r, item):
mylist.pop(i)
item = mylist[i]
mylist[i-1] += mylist[i]
mylist.pop(i)
else:
i += 1
print(mylist)
# ['a', 'bc', 'd', 'e', 'fg', 'h', 'i', 'j']
PS: You can add more options using more regex expressions for catching different cases
Merge items in list based on condition
result = [i.strip() for i in ''.join(a).split('/n') if i]
However you should post your attempt first.
Merging two list with certain condition
You want to loop over the indices, not the elements of the list.
So what we need here is for i in range(len(listA))
.
We can break this expression further to get a better understanding:
len(listA)
gives the number of elements in list A. Clearly, this solution will only work iflistA
andlistB
have the same number of elements. In your example,len(listA)
equals 5range(len(listA))
will iterate over a range of integers: from0
tolen(listA) - 1
. For our running example, this will berange(5)
, so from0
to4
for i in range(len(listA))
then just loops overi = [0, 1, 2, 3, 4]
.
listA = [2,0,0,5,6,0]
listB = [4,5,7,3,2,1]
listC = []
for i in range(len(listA)):
if listA[i] == 0:
listC.append(listB[i])
else:
listC.append(listA[i])
print(listC) # [2, 5, 7, 5, 6, 1]
I'll leave a couple of one-liners you can come back to once you are farther ahead in your python journey.
listC = [b if a == 0 else a for (a, b) in zip(listA, listB)]
list(map(lambda ab: ab[1] if ab[0] == 0 else ab[0], zip(listA, listB)))
Good luck!
Related Topics
Python Pip Install Fails: Invalid Command Egg_Info
How to Split a CSV File Row to Columns in Python
Retrieving Subfolders Names in S3 Bucket from Boto3
Python 3D Polynomial Surface Fit, Order Dependent
How to Skip Blank Line While Reading CSV File Using Python
Finding Non-Numeric Rows in Dataframe in Pandas
Python | Count Number of False Statements in 3 Rows
Converting Json into Newline Delimited Json in Python
Pandas - How to Compare 2 CSV Files and Output Changes
Run Multiple Python File Concurrently
Python3: Remove a Substring Between Two Delimiting Char
Calculate Monthly Returns from Daily Returns in Pandas(Cumpound)
Python - Outputting Variables to Txt File
Replace Empty Strings With None/Null Values in Dataframe