Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List joining
#1
Good day,

I have searched and read and tried options for days... I know it must be simple, yet here I am.

I am creating a list from two user input lists; list_a is a set of tasks that may change from day to day in number and name; and list_b, a set of people who may change from day to day in number. I need list_c (or more) to be an equal distribution of list_b elements to each list_a element. I have the first part, entering the data, saving it, retrieving if needed (they may be the same for a few days). I've dealt with out of range, randomizing, iteration, slicing and splicing, no duplicates, etc. But for some reason, because the lists are user imputed, and not always the same elements, and especially the same number of elements, I just can't seem to find a way to join them properly.

Example
Task list: a, b, c
People list: John, Joe, Karen, Billy, Bob, Lisa, Derek

Desired Output: a: John, Billy, Derek
b: Joe, Bob
c: Karen, Lisa

I'm a noob, I feel like I have exhausted my ability to ask search engines the question in a different way and I've read so many posts my brain hurts...

Any help would be appreciated.
DeatZ
Reply
#2
Looks like you want the task list to be: a, b, c, a, b, c, a, b, c, a
If there was just some kind of ITERATOR TOOL that would CYCLE through a list for as long as needed?

You can also use indexing and the modulo operator, but the above hint is better.

If you don't want to search any more after those hints, let me know and I'll give it to you straight
Reply
#3
(Dec-05-2022, 08:48 PM)deanhystad Wrote: Looks like you want the task list to be: a, b, c, a, b, c, a, b, c, a
If there was just some kind of ITERATOR TOOL that would CYCLE through a list for as long as needed?

You can also use indexing and the modulo operator, but the above hint is better.

If you don't want to search any more after those hints, let me know and I'll give it to you straight

Evening,

Found ITERTOOLS and CYCLE which are great, got it to cycle through endlessly. When I try to use that to combine the lists I'm back to where I've been with for loops, random. choice and such. The result is a partial list, or just a re-labled list..

any more hints?
Reply
#4
from itertools import cycle
numbers = []
letters = []

while number := input("Number: "):
    numbers.append(number)

while letter := input("Letters: "):
    letters.append(letter)

# And then magic happened.  POOF!

print(list(zip(letters, numbers)))
Output:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Number: 6 Number: Letters: a Letters: b Letters: c Letters: [('a', '1'), ('b', '2'), ('c', '3'), ('a', '4'), ('b', '5'), ('c', '6')]
The magic is that one of the zip sources (number or letter) becomes a cycle. Which one?
deatz likes this post
Reply
#5
Wow, so much less code than I had so far even.

Is there a way to produce the output as only
Output:
[('a', '1', '4'), ('b', '2', '5'), ('c', '3', '6')]
or will I have to pull that separately.

Just for a giggle for you, here was my rabbit hole; I made the lists static for troubleshooting as I have those entered with a def:
import random
from itertools import cycle

list_a = [
    'Hangar',
    'Trash',
    'Sweep',
    'Mop',
    'Labs'
]

list_b = [
    'John',
     'Kat',
     'Emile',
     'Noble 6',
     'Echo 216',
     'Billy',
     'Lenny',
     'Larry',
     'Sammi',
     'Ray-Ray',
     'Angel',
     'Kashaa',
     'Bri',
     'Amy',
     'Kipper',
     'Bernard'
]

random.shuffle(list_b)

# print(list_a)
# print(len(list_b))
# print(list_b)

list_c = [[]] * len(list_a)
# print(list_c)
x = 0

for i in list_b:
    try:
        iterator = cycle(list_a)
        new_element = random.choice(list_b)
        if new_element in list_c:
            pass
        else:
            list_c[x].append(list_a[x])
            list_c[x].append([new_element])
            x = x + 1
    except: IndexError
    continue

# print(list_a)
# print(list_b)
print(list_c)
output:
Output:
[['Hangar', ['Noble 6'], 'Trash', ['Kashaa'], 'Sweep', ['Kat'], 'Mop', ['Larry'], 'Labs', ['Lenny']], ['Hangar', ['Noble 6'], 'Trash', ['Kashaa'], 'Sweep', ['Kat'], 'Mop', ['Larry'], 'Labs', ['Lenny']], ['Hangar', ['Noble 6'], 'Trash', ['Kashaa'], 'Sweep', ['Kat'], 'Mop', ['Larry'], 'Labs', ['Lenny']], ['Hangar', ['Noble 6'], 'Trash', ['Kashaa'], 'Sweep', ['Kat'], 'Mop', ['Larry'], 'Labs', ['Lenny']], ['Hangar', ['Noble 6'], 'Trash', ['Kashaa'], 'Sweep', ['Kat'], 'Mop', ['Larry'], 'Labs', ['Lenny']]]
Confused

I also realized after playing with it some, it only uses a factor of the list, the remaining elements are left out.
We exit after one revolution through the first list
from itertools import cycle

list_a = [
    'Hangar',
    'Trash',
    'Sweep',
    'Mop',
    'Labs'
]

list_b = [
    'John',
     'Kat',
     'Emile',
     'Noble 6',
     'Echo 216',
     'Billy',
     'Lenny',
     'Larry',
     'Sammi',
     'Ray-Ray',
     'Angel',
     'Kashaa',
     'Bri',
     'Amy',
     'Kipper',
     'Bernard'
]


print(list(zip(list_a, list_b)))
output:
Output:
[('Hangar', 'John'), ('Trash', 'Kat'), ('Sweep', 'Emile'), ('Mop', 'Noble 6'), ('Labs', 'Echo 216')]

Stand by, for some reason PyCharm is not importing cycle now....

So, I think that is fixed, but I am still not getting your result.
from itertools import cycle

numbers = []
letters = []

while number := input("Number: "):
    numbers.append(number)

while letter := input("Letters: "):
    letters.append(letter)

# And then magic happened.  POOF!

print(list(zip(letters, numbers)))
_______________________
Output:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Number: 6 Number: Letters: a Letters: b Letters: c Letters: [('a', '1'), ('b', '2'), ('c', '3')]
Yoriz write Dec-07-2022, 06:50 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#6
You need to replace the magic poof! with actual code. If one of the lists is longer than the other, zip will stop when the shorter list runs out of values. You need to do something to prevent that.

Producing [('a', '1', '4'), ('b', '2', '5'), ('c', '3', '6')] would be difficult. Tuples are immutable, so you cannot add items once they are created. Producing [['a', '1', '4'], ['b', '2', '5'], ['c', '3', '6']] is relatively easy.
from itertools import cycle
baskets = []
items = []

while basket := input("Basket: "):
    baskets.append([basket])

while item := input("Items: "):
    items.append(item)

# Poof! Magic happens!
    basket.append(item)

print(baskets)
Output:
Basket: a Basket: b Basket: Items: 1 Items: 2 Items: 3 Items: 4 Items: 5 Items: [['a', '1', '3', '5'], ['b', '2', '4']]
Reply
#7
from itertools import cycle
baskets = []
items = []
 
while basket := input("Basket: "):
    baskets.append([basket])
 
while item := input("Items: "):
    items.append(item)
 
# Poof! Magic happens!
    basket.append(item)
 
print(baskets)
I can't finish my inputs and get this:

Error:
C:\Users\david\PycharmProjects\pythonProject\venv\Scripts\python.exe E:\DropBoxFiles\Dropbox\Programming\Python\ittertools_v2.py Basket: a Basket: b Basket: c Basket: Items: 1 Traceback (most recent call last): File "E:\DropBoxFiles\Dropbox\Programming\Python\ittertools_v2.py", line 12, in <module> basket.append(item) ^^^^^^^^^^^^^ AttributeError: 'str' object has no attribute 'append' Process finished with exit code 1
I'm using PyCharm, dunno if that makes a difference.

I appreciate all your help, it's frustrating that a seemingly simple task is wrecking my brain.
Reply
#8
Just in case it wasn't clear before. "# And then magic happened. POOF!" is a place holder for some missing Python code. You did not insert the required code.
deatz likes this post
Reply
#9
(Dec-08-2022, 01:42 AM)deanhystad Wrote: Just in case it wasn't clear before. "# And then magic happened. POOF!" is a place holder for some missing Python code. You did not insert the required code.

I haven't had much time to work with this, I tried some variations of cycle in place of "POOF" to no avail, also think it should be "baksets.append(item) instead of just basket.append(item)??

At any rate, I am still lost in the weeds.

Have a blessed day,
DeatZ
Reply
#10
from itertools import cycle
baskets = []
items = []
  
while basket := input("Basket: "):
    baskets.append([basket])
  
while item := input("Items: "):
    items.append(item)
  
for basket, item in zip(cycle(baskets), items):
    basket.append(item)
  
print(baskets)
Output:
Basket: A Basket: B Basket: Items: 1 Items: 2 Items: 3 Items: 4 Items: 5 Items: [['A', '1', '3', '5'], ['B', '2', '4']]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using a function: splitting, joining, and slicing a string Drone4four 2 4,848 Dec-27-2018, 07:52 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020