Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
lists in tkinter
#1
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)
Reply
#2
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)
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
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
Reply
#4
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"))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,367 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,259 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

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