简体   繁体   English

如何在特定条件下以特定顺序将列表放入一个更大的列表中? -Python 3.x

[英]How to put lists into one larger list in a certain order for certain conditions? - Python 3.x

Right now, I have a code that look something along the lines of: 现在,我有一个代码看起来类似于以下内容:

def get_newdeck(choice, P1, P2, P3):
    deck = []
    if choice == 1:
        deck = P2+P1+P3
        return deck
    elif choice == 2:
        deck = P1+P2+P3
        return deck
    else:
        deck = P1+P3+P2
        return deck

This is part of a code that is part of a code for a magic trick, which guesses the user's card from a 'deck' of 21. choice is a user input (integer that is either 1, 2, or 3) for which pile the card was previously in, P1, P2, P3 are lists that represent the three piles; 这是代码的一部分,而该代码也是魔术技巧的代码的一部分,魔术技巧从21的“ deck”中猜测用户的牌。 choice是为其输入的用户输入(整数为1、2或3)该卡以前在其中, P1, P2, P3是代表这三堆的列表; more is explained about these piles below. 有关这些堆的更多信息,请参见下文。
An algorithmic card trick works as follows: 算法卡技巧如下:

  1. The magician deals 21 shuffled playing cards face up into three piles working left-to-right row-by-row. 魔术师将21张打乱的扑克牌正面朝上分成三堆,从左到右逐行工作。 The first time the magician does this an audience member is asked to choose one of the cards and keep their choice secret. 魔术师第一次执行此操作时,要求观众选择其中一张卡,并对其选择保密。

  2. The magician asks the audience member to say whether their card is in the first, second or third pile. 魔术师要求听众说出他们的牌是在第一堆,第二堆还是第三堆中。

3. The magician collects the cards pile by pile ensuring the selected pile is placed in between the other two piles. 3.魔术师一堆一堆地收集卡片,确保将选定的堆放置在其他两个堆之间。

  1. Steps 1-3 are repeated 2 more times. 将步骤1-3再重复2次。

  2. Once these steps are completed, the chosen card will 'magically' be in the middle of the deck of 21 cards. 完成这些步骤后,所选卡片将“神奇地”位于21张卡片组的中间。

The step in question is step three, and I am trying to make it look less repetitive. 有问题的步骤是第三步,我正在尝试使其看起来不太重复。

Is there a way that I could get my code (shown above) to work using a loop? 有没有办法让我的代码(如上所示)使用循环工作? FYI I am using Python-3.x 仅供参考,我正在使用Python-3.x

If you want it, here is the full code - I know it's messy, and there are no comments, but I am trying to fix it, starting with the 'messy' part. 如果需要的话,这里是完整的代码-我知道它很杂乱,没有注释,但是我正在尝试从“混乱”部分开始进行修复。

import random

def get_cards():
    nums, suits=['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King'], ['Hearts','Clubs','Diamonds','Spades']
    cards_dealt=[]
    while len(cards_dealt) < 22:
        card = random.choice(nums) + " of " + random.choice(suits)
        if card not in cards_dealt:
            cards_dealt.append(card)
        else:
            continue        
    return cards_dealt


def get_piles(deck):
    P1, P2, P3 = [], [], []
    for i in range(21):
        if i%3 == 0:
            P1.append(deck[i])
        elif i%3 == 1:
            P2.append(deck[i])
        else:
            P3.append(deck[i])
    return P1, P2, P3

#####################################
def get_newdeck(choice, P1, P2, P3):
    deck = []
    if choice == 1:
        deck = P2+P1+P3
        return deck
    elif choice == 2:
        deck = P1+P2+P3
        return deck
    else:
        deck = P1+P3+P2
        return deck
#####################################

def main():
    deck = get_cards()
    print("Choose a card and remember it")
    for x in range(3):
        P1, P2, P3 = get_piles(deck)
        piles = {'Pile 1':P1, 'Pile 2': P2, 'Pile 3':P3} 
        for numpile, pile in sorted(piles.items()):
            print()
            print(numpile,': ')
            for card in pile:
                print(card)
        print()
        choice = 0
        while choice > 3 or choice < 1:
            while True:
                try:
                    choice = int(input("Which pile is your card in? (1-3)? > "))
                    break
                except ValueError:
                    print("Must be a number")
        deck = get_newdeck(choice, P1, P2, P3)
    print()
    print('Your card is {}'.format(deck[10]))


main()

You could do something like this: 您可以执行以下操作:

def get_newdeck(choice, P1, P2, P3):
    chunks = [P1, P2, P3]
    idx = choice-1
    deck = chunks[(idx-1) % 3]+chunks[idx % 3]+chunks[(idx+1) % 3]
return deck

I'm taking idx=choice-1 so their choice is 0, 1, or 2 which would match up well with the three chunks of cards in the chunks list. 我采用idx=choice-1所以他们的选择是0、1或2,这将与chunks列表中的三张纸牌很好地匹配。 Since chunks[idx] is their selected pile now, and chunks[idx-1] and chunks[idx+1] are the piles before and after their selected pile respectively, you create deck by putting their pile between the other two. 现在, chunks[idx]是他们选择的桩, chunks[idx-1]chunks[idx+1]分别是他们选择的桩之前和之后的桩,因此可以通过将桩放置在其他两个桩之间来创建deck The % (modulo operation) just makes sure that if we go outside of the 0,1,2 range we wrap the result back into that range. % (模运算)只是确保如果我们超出0,1,2范围,我们会将结果包装回该范围。

This is easy to visualize if you image their choice had been 2. Then the piles are just in P1, P2, P3 order. 如果您对他们的选择进行了想象,这很容易形象化。然后,桩就按照P1,P2,P3的顺序排列。

If the user selects the first pile, idx would be 0, and the pile before that would be -1. 如果用户选择第一个桩,则idx将为0,而在此之前的桩将为-1。 Modulo 3 this becomes 2, which is the last pile in the sequence. 模数3变为2,这是序列中的最后一个堆。

First of all, I don't think your code looks that repetitive for 3 cases. 首先,我不认为您的代码在3种情况下看起来都是重复的。 But for the sake of exchanging idea, here's what I think: 但是为了交换想法,我的想法是:

since you want choice position to be swapped with middle element, in this case index 1 (a list with three elements, the indexes would be 0, 1, 2 ), you can do 由于您希望choice位置与中间元素交换,在本例中为索引1 (包含三个元素的列表,索引将为0, 1, 2 ),因此您可以执行

piles[choice - 1], piles[1] = piles[1], piles[choice - 1]

(of course if choice = 2 , nothing changes) (当然,如果choice = 2 ,则什么都不会改变)

The test code: 测试代码:

def get_newdeck(choice, P1, P2, P3):
    piles = [P1, P2, P3]
    piles[choice - 1], piles[1] = piles[1], piles[choice - 1]
    deck = []
    for pile in piles:
        deck.extend(pile)
    return deck


if __name__ == "__main__":
    choice = 1
    P1 = [1, 2]
    P2 = [3, 4]
    P3 = [5, 6]
    deck = get_newdeck(choice, P1, P2, P3)
    print(deck)

I don't think there is any serious problem with your code. 我认为您的代码没有任何严重的问题。 For a list with 3 elements it is much readable if you do what you are already doing rather then writing unnecessary messy loops. 对于包含3个元素的列表,如果您已经在做,而不是编写不必要的混乱循环,那么可读性就很高。

I was playing a bit with your code and I changed just a few things, mainly the looks :) 我在玩你的代码,我只做了几件事,主要是外观:)

import random

def get_cards():
    nums, suits=['A','2','3','4','5','6','7','8','9','10','J','Q','K'], [u'\u2665',u'\u2663',u'\u2666',u'\u2660']
    cards_dealt=[]
    while len(cards_dealt) < 22:
        card = random.choice(nums) + random.choice(suits)
        if card not in cards_dealt:
            cards_dealt.append(card)
        else:
            continue        
    return cards_dealt


def get_piles(deck):
    P1 = [deck[i] for i in range(0,21,3)]
    P2 = [deck[i] for i in range(1,21,3)]
    P3 = [deck[i] for i in range(2,21,3)]
    return P1, P2, P3

#####################################
def get_newdeck(choice, P1, P2, P3):
    deck = P1+P3+P2
    if choice == 1:
        deck = P2+P1+P3
    elif choice == 2:
        deck = P1+P2+P3
    return deck
#####################################

def main():
    deck = get_cards()
    print("Choose a card and remember it")
    for x in range(3):
        P1, P2, P3 = get_piles(deck)
        piles = {'Pile 1':P1, 'Pile 2': P2, 'Pile 3':P3} 
        for numpile, pile in sorted(piles.items()):
            print(numpile+': ', end='\t')
            for card in pile:
                print(card, end='\t')
            print()
        print()
        choice = 0
        while choice > 3 or choice < 1:
            while True:
                try:
                    choice = int(input("Which pile is your card in? (1-3)? > "))
                    break
                except ValueError:
                    print("Must be a number")
        deck = get_newdeck(choice, P1, P2, P3)
    print()
    print('Your card is {}'.format(deck[10]))

main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将列表显示为某个十进制数-Python 3.x - Displaying A List to a Certain Decimal - Python 3.x 列表(数组)中某个范围内的随机样本| Python 3.x - Random sample within a certain range in a list (array) | Python 3.x 在Python 3.x中,如何替换列表中的某些项目,然后将列表打印为字符串 - In Python 3.x, how do I replace certain items in a list then print list as a string 在python 3.x中列出 - Lists in python 3.x 如何使用python从列表列表中删除某些列表? - How to remove certain lists from a list of lists using python? Python 3.x函数:将字符串转换为列表并输出不包含某些字符的输出 - Python 3.x function:Converting string to list and printing output which excludes certain characters Python 3.x — 根据另一个列表对一个列表进行排序,然后返回已排序的两个列表 - Python 3.x — sort one list based on another list and then return both lists sorted 如果其中的一个单词在Python中不包含某些字符,如何从列表列表中删除一行? - How to remove a row from a list of lists if one of the words in it does not contain certain characters in Python? 分析文本文件中的Python 3.x中的某些属性 - Analyze a text file for certain attributes in Python 3.x Python 3.x:如何比较包含字典的两个列表,其中顺序无关紧要 - Python 3.x: How to compare two lists containing dictionaries where order doesn't matter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM