1. Welcome! Please take a few seconds to create your free account to post threads, make some friends, remove a few ads while surfing and much more. ClutchFans has been bringing fans together to talk Houston Sports since 1996. Join us!

Python help

Discussion in 'BBS Hangout' started by Haymitch, Sep 21, 2018.

  1. Haymitch

    Haymitch Custom Title

    Joined:
    Dec 22, 2005
    Messages:
    28,371
    Likes Received:
    24,024
    I'm taking a basic Python class and occasionally have one-off questions. Google/Stackoverflow searches usually help but not always. There's also an online tutoring service but they sometimes tell me they can't figure out the issue.

    I'm sure there are at least a few people here who know python.

    Here's where I'm stuck. This is just a snippet of the program, partially edited. All I want here is to print the Cartesian product of the two lists in this format:

    (A, 1) (A, 2) (A, 3)
    (B, 1) (B, 2) (B, 3)
    (C, 1) (C, 2) (C, 3)

    Code:
    import itertools
    
    predef_listA = [A,B,C]
    predef_listB = [1,2,3]
    
    welcome = str(input('Type Yes'))
    if welcome == 'Yes':
        print('Here is the first list: ', predef_listA)
        print('Here is the second list: ', predef_listB)
        input('Press Enter.')
        from itertools import product
        for list1, list2 in product(predef_listA,predef_listB):
            print(list1, list2)

    Right now it's printing out like this:
    A 1
    A 2
    A 3
    B 1
    B 2
    etc...

    (For my purposes I don't care if it prints out with parentheses, brackets, or neither.)

    I'm wondering if I should abandon itertools and do a for loop?
     
  2. DonkeyMagic

    DonkeyMagic Member
    Supporting Member

    Joined:
    May 22, 2006
    Messages:
    21,620
    Likes Received:
    3,505
  3. Air Langhi

    Air Langhi Contributing Member

    Joined:
    Aug 26, 2000
    Messages:
    21,990
    Likes Received:
    6,755
    The easiest way is to use two for loops

    If you want the answer:


    predef_listA = ['A','B','C']
    predef_listB = [1,2,3]

    welcome = str(input('Type Yes'))
    if welcome == 'Yes':
    print('Here is the first list: ', predef_listA)
    print('Here is the second list: ', predef_listB)
    input('Press Enter.')
    from itertools import product
    for i in predef_listA:
    for j in predef_listB:
    print("({},{})".format(i, j),end="")
    print("\n")
     
    No Worries and Haymitch like this.
  4. cheke64

    cheke64 Member

    Joined:
    May 12, 2009
    Messages:
    27,254
    Likes Received:
    19,555
    Misleading title. Thought this was about you unable to flush your python in the toilet
     
    Surfguy likes this.

Share This Page