Python Forum
lists in tkinter - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: lists in tkinter (/thread-27435.html)



lists in tkinter - erock - Jun-06-2020

Hi,
totaly new to this python stuff
I have 2 lists
i want to be able to randomly pick one item from each list one at a time
this code doesen't do the job
( for an example first i will get dog ,then hippo,then cat and etc)
Sad
thanks

import tkinter as tk
import random
root=tk.Tk()
def rand():

    animalist1=['dog','cat','cow','horse','duck','bird']
    animalist2 = ['Hippo', 'Bat', 'Fish', 'Whale', 'Bear', 'Monkey']

    seqs = [animalist1,animalist2]
    animalrand1 = random.choice(random.choices(seqs, weights=map(len, seqs))[0])


    #animalrand1 = random.choice(animalist1)
    #animalrand2 = random.choice(animalist2)
    label.configure(text=animalrand1)
    #label.configure(text=animalrand2)



RE: lists in tkinter - menator01 - Jun-06-2020

You could try something like this
l1 = ['a','b','c','d']
l2 = [1,2,3,4]
combined = list(zip(l1,l2))
import random as rnd
print(rnd.choice(combined))
Output:
('b', 2)



RE: lists in tkinter - bowlofred - Jun-06-2020

I might create a separate generator. Then it could loop over the lists and randomly pick from each.

def rand_from_seq_lists():
    lists = [
              ['dog','cat','cow','horse','duck','bird'],
              ['Hippo', 'Bat', 'Fish', 'Whale', 'Bear', 'Monkey'],
            ]
    while True:
        for sublist in lists:
            yield random.choice(sublist)


picks = 4
gen = rand_from_seq_lists()
print(f"Here are {picks} choices, randomly from each list sequentially chosen.")
for _ in range(picks):
    print(next(gen))
Output:
Here are 4 choices, randomly from each list sequentially chosen. bird Bat horse Bear



RE: lists in tkinter - erock - Jun-06-2020

in both cases I get more then one random choice
I think I worked it out with a simple if else statement
but thank you so much for your help

import tkinter as tk
import random
root=tk.Tk()
def rand():

    animalist1=['dog','cat','cow','horse','duck','bird']
    animalist2 = ['Hippo', 'Bat', 'Fish', 'Whale', 'Bear', 'Monkey']

    animalrand1 = random.choice(animalist1)
    animalrand2 = random.choice(animalist2)

    if label.cget("text") in animalist1:
        label.configure(text=animalrand2)
    else:
        label.configure(text=animalrand1)
    #print (label.cget("text"))