2017-08-03 11 views
-3

不确定为什么这被拒绝了Stack没有其他答案。 - 所有其他示例使用集合,这是这里唯一的方法,显示如何识别同一个int在另一个列表中的相同位置。Python比较两个列表,并以相同的顺序返回相同数量的匹配,以更pythonic的方式

的回答感谢兆字节:

x = [3,5,6,7] 
y = [3,5,7,9] 
compare_order = [1 if i==j else 0 for i, j in zip(x,y)] 
#returns [1,1,0,0] 

寻找一个更Python的方式为(更换if语句)确定如果我的两个列表的元素以相同的顺序。我已经切分了两个列表,并将元素转换为d1等,如下所示。不能使用套只是想知道,如果列表1 ==第N list2中的第N个

roll = random.sample(range(1,9), 4) 
r1 = roll[0:1] 
r2 = roll[1:2] 
r3 = roll[2:3] 
r4 = roll[3:4] 
choice = int(1243) 
SliceChoice = [int(x) for x in str(choice)] 
d1 = SliceChoice[0:1] 
d2 = SliceChoice[1:2] 
d3 = SliceChoice[2:3] 
d4 = SliceChoice[3:4] 

x = [] 
    if d1 == r1: 
     print ('got one') 
     x = x + 1 
    if d2 == r2: 
     print ('got one') 
     x = x + 1 
    if d3 == r3: 
     print ('got one') 
     x = x + 1 
    if d4 == r4: 
     print ('got one') 
     x =x + 1 

if x == (4): 
    print('well done') 

确定,所以它已经有一段时间,所以我想我应该张贴我的最终版本感谢您的帮助。

import random 


    def start(): 
     """ this function is used to initialise the users interaction with the game 
     Primarily this functions allows the user to see the rules of the game or play the game""" 
     print ('Mastermind, what would you like to do now?\n') 
     print ('Type 1 for rules') 
     print ('Type 2 to play') 
     path = input('Type your selection 1 or 2: ') 
     if path == '1': 
      print ('Great lets look at the rules') 
      rules() 
     elif path == '2': 
      print('Great lets play some Mastermind!\n') 
      begingame() 
      start() 
     else: 
      print('that was not a valid response there is only one hidden option that is not a 1 or a 2') 
      start() 

    def rules(): 
     """This just prints out the rules to the user.""" 
     print ('The rules are as follows:\n') 
     print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n') 
     print ('2)You will have 12 attempts to guess the correct number.\n') 
     print ('3)Whites represent a correct number that is not in the correct order\n') 
     print ('4)Reds represent a correct number in the correct order.\n') 
     print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n') 
     print ('6)to WIN you must guess the 4 numbers in the correct order.\n') 
     print ('7)If you run out of guesses the game will end and you lose.\n') 
     print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.') 
     start() 

    def makeRandomWhenGameStarts(): 
     """A random 4 digit number is required this is created as its own 
     variable that can be passed in at the start of the game, this allows the user 
     to guess multiple times against the one number.""" 

     #generate a 4 digit number 
     num = random.sample(range(1,9), 4) 

     #roll is the random 4 digit number as an int supplied to the other functions 
     roll = int(''.join(map(str,num))) 

     return roll 

    def begingame(): 
     """This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is 
     passed in anbd then an exception handling text input is used to ask the user for their guees """ 
     print ('please select 4 numbers') 

     #bring in the random generated number for the user to guess. 
     roll    = makeRandomWhenGameStarts() 
     whiteResults  = [] 
     redResults   = [] 
     collectScore  = [] 
     guessNo    = 0 

     #setup the while loop to end eventually with 12 guesses finishing on the 0th guess. 
     guesses = 12 
     while (guesses > 0): 
      guessNo = guessNo + 1 
      try: 
       #choice = int(2468) #int(input("4 digit number")) 
       choice = int(input("Please try a 4 digit number: ")) 
       if not (1000 <= choice <= 9999): 
        raise ValueError() 
        pass 
      except ValueError: 
       print('That was not a valid number, you lost a turn anyway!') 
       pass 
      else: 
       print ("Your choice is", choice) 

      #Use for loops to transform the random number and player guess into lists 
      SliceChoice = [int(x) for x in str(choice)] 
      ranRoll  = [int(x) for x in str(roll)] 

      #Take the individual digits and assign them a variable as an identifier of what order they exist in. 
      d1Guess = SliceChoice[0:1] 
      d2Guess = SliceChoice[1:2] 
      d3Guess = SliceChoice[2:3] 
      d4Guess = SliceChoice[3:4] 

      #combine the sliced elements into a list 
      playGuess = (d1Guess+d2Guess+d3Guess+d4Guess) 

      #Set reds and whites to zero for while loop turns  
      nRed = 0 
      nWhite = 0 

      #For debugging use these print statements to compare the guess from the random roll 
      # print(playGuess, 'player guess') 
      # print(ranRoll,'random roll') 

      #Use for loops to count the white pegs and red pegs 
      nWhitePegs = len([i for i in playGuess if i in ranRoll]) 
      nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)]) 


      print ('Oh Mastermind that was a good try! ') 

      #Take the results of redpegs and package as turnResultsRed 
      TurnResultsRed = (nRedPegs) 

      #Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite 
      TurnResultsWhite = (nWhitePegs - nRedPegs) #nWhite-nRed 

      #Create a unified list with the first element being the guess number 
      # using guessNo as an index and storing the players choice and results to feedback at the end 
      totalResults = (guessNo,choice , TurnResultsWhite ,TurnResultsRed) 

      # collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses 
      collectScore.append(totalResults) 

      #End the while loop if the player has success with 4 reds  
      if nRed == (4): 
       print('Congratulations you are a Mastermind!') 
       break  

      #Return the results of the guess to the user 
      print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n') 

      #remove 1 value from guesses so the guess counter "counts down" 
      guesses = guesses -1 
      print ('You have', guesses, "guesses left!") 

     #First action outside the while loop tell the player the answer and advise them Game Over 
     print('Game Over!') 
     print('The answer was', roll) 

     #At the end of the game give the player back their results as a list 
     for x in collectScore: 
      print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites') 


    if __name__ == '__main__': 
     start() 
+4

显示原始2所列出并期望输出 –

+1

如果两个列表的长度相同,如果它们的所有元素都相等,那么它们将相等,所以不需要像这样逐元检查顺序。 – jonrsharpe

+0

是的,这是一个游戏 – Aza

回答

4

尝试这一个列表:

x = [3,5,6,7] 
y = [5, 7, 9] 
compare_order = [1 if i==j else 0 for i, j in zip(x,y)] 
+0

这将做到这一点,谢谢 – Aza

+0

@Aza请接受答案,如果这项工作 – MegaBytes

+0

完成,感谢您的帮助 – Aza

-1

我认为,简单地比较与==操作符的两个列表应该做的工作

>>> a = [0,3,4,5] 
>>> b = [0,3,5,4] 
>>> a == b 
False 
>>> c = [0,3,4,5] 
>>> a == c 
True 

或者,你也许可以试试这个:

>>> for index, item in enumerate(a): 
...  if item == b[index]: 
...    print "same" 
...  else: 
...    print "different" 
0
l1, l2 = [1, 2, 5], [1, 2, 3] 
len(l1) == len(l2) and all(i == j for i, j in zip(l1, l2)) 
+1

你能否给你的代码添加一些上下文? – ppperry

0

您应该使用a 过滤器功能:

list1 = [1, 2, 3, 4] 
list2 = [1, 3, 2, 4, 5] 
result = list(filter(lambda i: list1[i]==list2[i], range(0, min(len(list1), len(list2))))) 
print(len(result)) 

假设你的函数返回2在我的例子中,因为数字1和4在两个列表中的相同位置这里是可能性。

请注意,过滤器函数将0和两个列表之间的最小长度之间的值范围作为输入。然后过滤掉两个列表中没有指向相同值的所有索引。

所以结果基本上包含两个列表中包含相同值的所有索引。

0

我会这样做。 (没有pythonic,我知道!)

list1 = [4, 2, 3, 1, 5, 6] 
list2 = [6, 4, 2] 
list3 = [4, 2, 3, 1, 5, 6] 

equals = 1 

for i in range(0, len(list1)): 
    print("{0} e {1}".format(list1[i], list3[i])) 
    if list1[i] != list3[i]: 
     equals = 0 
     break 

if equals == 1: 
    print("equals") 
else: 
    print("not equals") 
0
list1 = [1,2,3,4,4,5,5] 
list2 = [1,1,7,4,8,5,6] 

我们可以用一个正常的嵌套的for循环如下:

for i, v in enumerate(list1): 
    for i1, v1 in enumerate(list2): 
     if (i==i1) & (v==v1): 
      print(i,v) 

它打印相匹配的索引和值

输出

0 1 
3 4 
5 5 

同样可以转换成嵌套列表理解

In [21]:[(i,v) for i1, v1 in enumerate(list2) for i, v in enumerate(list1) if (i==i1) & (v==v1)] 
Out[21]: 
[(0, 1), (3, 4), (5, 5)] 

返回的(索引,值)匹配

相关问题