Merge every certain number of items in a list - python

I have a list like this
items= ['e', '4', 'e', 'e', '4', '5', '4', '8', 'a', '8', '6', 'd', '8', 'a', 'e', '1', 'b', '6', '2', '1', '6', 'a', 'a', 'a', '2', 'b', 'd', '6', '7', '7', '9', '2']
I want to edit the list so that every 4 items in the list get merged like this
items=['e4ee', '4548', 'a86d', '8ae1', 'b621', '6aaa', '2bd6', '7792']
Edit: My mistake for wording. By not creating a new list I meant by putting the arranged elements into a separate list like this
items = ['e', '4', 'e', 'e', ...
items2 = ['e4ee', '4548', ...

You could do it like this although this does create a new list:
items = ['e', '4', 'e', 'e', '4', '5', '4', '8', 'a', '8', '6', 'd', '8', 'a', 'e', '1', 'b', '6', '2', '1', '6', 'a', 'a', 'a', '2', 'b', 'd', '6', '7', '7', '9', '2']
items = [''.join(items[i:i+4]) for i in range(0, len(items), 4)]
print(items)
Output:
['e4ee', '4548', 'a86d', '8ae1', 'b621', '6aaa', '2bd6', '7792']

If you absolutely do not want to create a new list (as stated):
result_len = len(items) // 4
for i in range(result_len):
j = (i*4)
items[i] = ''.join(items[j:(j+4)])
for i in range(len(items) - 1, result_len - 1, -1):
del items[i]
Does exactly len(items) iterations and never creates a new list.
The first loop updates the first result_len items in the list to the desired values. The second one deletes the rest of the items from it.
EDIT: Whoops, had a bug there. Now it should be correct.

Related

How to join up 2 list with a distinct format? [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 4 months ago.
how do I join these 2 list
suits = ['C','D','H','S']
and
value = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
to A-C, 2-C and so forth until K-S?
i tried doing these format but it didn't work
def options():
i = 13
option1 = []
while True:
option = input()
suits = ['C','D','H','S']
value = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
cards = str
_input = int(input())
suit = suits[_input-1]
for j in value:
option1 = print(j+"-"+suit+",", end="")
return option1
already answered it
i did this instead
'''suits = ['C','D','H','S']
value = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
for i in suits:
for j in value:
cards = print(j+"-"+i, end=",")'''

Issue with single line nested for loop in Python

I have data that exports in a string
output = '012345678910abcdefghijkl'
cleaned_output = [output[index:index + 4] for index in range(0, len(output), 4)]
cleaned_output = [cleaned_output[i][item] for i in range(0, len(cleaned_output)) for item in range(0,len(cleaned_output[i]))]
Which returns:
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
However, I am looking to return the below, any ideas on where I am going wrong?
[['0', '1', '2', '3'], ['4', '5', '6', '7'], ['8', '9', '1', '0'], ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
You should just split your input into chunks of 4 and then convert them directly to lists:
cleaned_output = [list(output[i:i+4]) for i in range(0, len(output), 4)]
Output:
[['0', '1', '2', '3'], ['4', '5', '6', '7'], ['8', '9', '1', '0'], ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]

How to format list in python

So I am trying to format a list for this:
['w', 'e', '5', 'p', '4', '7', '2', 'w']
to this:
we5p472w
Any idea how to do this?
NOTE: this is a LIST, not a STRING
Use the join() method:
l = ['w', 'e', '5', 'p', '4', '7', '2', 'w']
print (''.join(l))
Outut:
we5p472w
You can use any expression to join your list elements:
print (' '.join(l))
Output:
w e 5 p 4 7 2 w
Code:
myList = ['w', 'e', '5', 'p', '4', '7', '2', 'w']
myString = "".join(myList)
print(myString)
Output:
$ we5p472w
list1 = ['w', 'e', '5', 'p', '4', '7', '2', 'w']
print("".join(list1))
returns we5p472w
check https://www.geeksforgeeks.org/join-function-python/ for a more detail explanation and more examples

Array Exchange and Reversing problem on Code Wars

# before
my_list = ['a', 'b', 'c']
other_list = [1, 2, 3]
exchange_with(my_list, other_list)
# after
my_list == [3, 2, 1]
other_list == ['c', 'b', 'a']
So I just finished solving the problem and I thought i had solved it with my solution below which was
def exchange_with(a, b):
a , b = b , a
print(a[::-1])
print("\n")
print(b[::-1])
and the solution comes out right but when I submit it it says
Test Results:
Log (MY RESULTS)
['c', 'b', 'a']
['7', '6', '5', '4', '3', '2', '1']
====================================================
['1', '2', '3', '4', '5', '6', '7'] should equal ['c', 'b', 'a']
['a', 'b', 'c'] should equal ['7', '6', '5', '4', '3', '2', '1']
I am very confused on what I did wrong I swapped each list and reversed it but it won't let me submit my solution
from what I understand here:
# before
my_list = ['a', 'b', 'c']
other_list = [1, 2, 3]
exchange_with(my_list, other_list)
# after
my_list == [3, 2, 1]
other_list == ['c', 'b', 'a']
you have to mutate the lists and the 'Test results' will evaluate your mutation, in which case you can try:
def exchange_with(my_list, other_list):
my_list[:], other_list[:] = other_list[::-1], my_list[::-1]
how it works (should not be used in your solution):
my_list = ['c', 'b', 'a']
other_list = ['7', '6', '5', '4', '3', '2', '1']
exchange_with(my_list, other_list)
print(my_list)
print(other_list)
output:
['1', '2', '3', '4', '5', '6', '7']
['a', 'b', 'c']

How to combine 'like' elements within nested list?

I have 3 nested lists:
STEP = [['S', '1', 'B', '3'], ['S', '3', 'B', '11'], ['S', '5', 'B', '12'], ['S', '4', 'B', '13'], ['S', '2', 'B', '14']]
TRANSITION = [['T', '2', 'B', '4'], ['T', '7', 'B', '4'], ['T', '3', 'S', '4'], ['T', '5', 'S', '5'], ['T', '1', 'S', '2'], ['T', '8', 'S', '2'], ['T', '6', 'S', '1'], ['T', '9', 'S', '2'], ['T', '4', 'S', '1'], ['T', '10', 'S', '1']]
BRANCH = [['B', '3', 'T', '1'], ['B', '3', 'T', '7'], ['B', '4', 'S', '3'], ['B', '11', 'T', '3'], ['B', '11', 'T', '5'], ['B', '12', 'T', '6'], ['B', '12', 'T', '8'], ['B', '13', 'T', '4'], ['B', '13', 'T', '9'], ['B', '14', 'T', '2'], ['B', '14', 'T', '10']]
Each element holds information as such:
# Example
STEP[0] = ['S', '1', 'B', '3']
Where:
'S' is the STEP type
'1' is the STEP number id
'B' is the linked BRANCH type
'3' is the linked BRANCH number id
Starting from a STEP the data is all linked, so using the linked reference you can find the next element and the next until another STEP is reached.
This is some parameters of the data:
STEPS are connected to single BRANCHES
BRANCHES are connected to one or more TRANSITIONS
TRANSITIONS can be connected to a single BRANCH or STEP
The BRANCH data can have a fork where a single BRANCH id has one or more options for TRANSITIONS.
I would like to combine these forks to the same `BRANCH' id, ie:
# BRANCH[0] and BRANCH[1] both have an id of '3'
# therefore, need to be combined
BRANCH[0] = ['B', '3', 'T', ['1', '7']]
This should be done to create a new list that combines all 'like' BRANCHES.
My attempt thus far (did not get very far):
for i in B:
if i[1] == B['all except current i'][1]
# append the branch id and the two transitions
I'm pretty sure there are easier ways, but based on your example, you can try :
BRANCH = [['B', '3', 'T', '1'], ['B', '3', 'T', '7'], ['B', '4', 'S', '3'], ['B', '11', 'T', '3'], ['B', '11', 'T', '5'], ['B', '12', 'T', '6'], ['B', '12', 'T', '8'], ['B', '13', 'T', '4'], ['B', '13', 'T', '9'], ['B', '14', 'T', '2'], ['B', '14', 'T', '10']]
tmp = {}
final = []
for x in BRANCH:
if not f"{x[0]}-{x[1]}" in tmp:
tmp[f"{x[0]}-{x[1]}"] = [x[3]]
else:
tmp[f"{x[0]}-{x[1]}"].append(x[3])
for k, v in tmp.items():
one, two = k.split("-")
for x in BRANCH:
if x[0] == one and x[1] == two:
if not [one, two, x[2], v] in final:
final.append([one, two, x[2], v])
print(final)
[['B', '3', 'T', ['1', '7']], ['B', '4', 'S', ['3']], ['B', '11', 'T', ['3', '5']], ['B', '12', 'T', ['6', '8']], ['B', '13', 'T', ['4', '9']], ['B', '14', 'T', ['2', '10']]]
Demo
You can use a test for similarity of the branches and then loop over the branches checking similarity. The rest is just guarding against duplicates and massaging the data to a list of lists. I did randomize the data and add another item to check that it wouldn't choke on more than a pair of similar branches.
# Check similarity (first three fields equal).
def similar_p(one, two):
for item in range(len(one) - 1):
if one[item] != two[item]:
return False
return True
# Data. Works sorted and not.
branches = [
['B', '14', 'T', '2'],
['B', '12', 'T', '6'],
['B', '14', 'T', '10'],
['B', '13', 'T', '4'],
['B', '3', 'T', '9'],
['B', '12', 'T', '8'],
['B', '13', 'T', '9'],
['B', '3', 'T', '7'],
['B', '4', 'S', '3'],
['B', '11', 'T', '5'],
['B', '3', 'T', '1'],
['B', '11', 'T', '3'],
]
merge_dict = {}
# Loop over branches. Uncomment print statements to watch the action.
for i in range(len(branches)):
# print('check for similars to branch {}'.format(branches[i]))
# try/except to ensure the dictionary item is actually there.
try:
# print(merge_dict[tuple(branches[i][0:3])])
if branches[i][3] not in merge_dict[tuple(branches[i][0:3])]:
merge_dict[tuple(branches[i][0:3])].append(branches[i][3])
# print('initial appending to branch {}'.format(branches[i]))
except (KeyError):
merge_dict[tuple(branches[i][0:3])] = [branches[i][3]]
# print('starting branch {}'.format(branches[i]))
for j in range((i + 1), len(branches), 1):
if similar_p(branches[i], branches[j]):
if branches[j][3] not in merge_dict[tuple(branches[i][0:3])]:
merge_dict[tuple(branches[i][0:3])].append(branches[j][3])
# print('appending similar branch {} to branch {}'.format(branches[j], branches[i]))
merged = list()
# Massage into a list. Sorting is on you, kid.
for k,v in merge_dict.items():
if len(v) == 1:
merged.append([*k, *v])
else:
merged.append([*k, v])
print(merged)
Output:
[['B', '14', 'T', ['2', '10']], ['B', '12', 'T', ['6', '8']], ['B', '13', 'T', ['4', '9']], ['B', '3', 'T', ['9', '7', '1']], ['B', '4', 'S', '3'], ['B', '11', 'T', ['5', '3']]]

Categories

Resources