简体   繁体   English

比较列表的最有效方法 Python

[英]Most efficient way to compare lists Python

How can I compare lists to one another.如何将列表相互比较。 I am looking to compare the first - fourth digit of two lists.我正在寻找比较两个列表的第一个 - 第四个数字。 I'm aware of being able to do if list[1] == list[1]: but id assume there is a more efficient way to get it done.我知道能够做到if list[1] == list[1]:但我假设有一种更有效的方法来完成它。 Thank you.谢谢你。 I don't want to compare the lists overall, just x part of one list to x part of another我不想比较整个列表,只是一个列表的 x 部分与另一个列表的 x 部分

import random
import replit
import numpy
import time
number = 0
answer = 0
guesses = 0
x = 0
useranswer = []
generated = []
for i in range (0,4):
  num = random.randrange(1,9)
  generated.append(num)
replit.clear()
print("---------------------------------------------------------------------\nWelcome to MASTERMIND! you must guess the number that was generated!\n---------------------------------------------------------------------\n")
def useranswer():
  answer = str(input("Select a 4 digit number: "))
  if len(answer) != 4:
    print("Invalid answer type")
    time.sleep(999999999)
    answer = ' '
  else:
    useranswer = list((str(answer)))
  
  
if useranswer == generated:
  print("Good job! You became the MASTERMIND in one turn!")
else: 
  while useranswer != generated:
    useranswer()
    guesses +=1
    if useranswer == generated:
      print("You have become the mastermind in " + guesses + " tries!")
    else:
      c = numpy.intersect1d(useranswer, generated, return_indices=True)[1]
      print("You got " + c + " correct! ")```

You can always use list slicing to compare the specified range of items between lists.您始终可以使用列表切片比较列表之间的指定项目范围

a = [1, 2, 3, 4, 7, 8]
b = [1, 2, 3, 4, 5, 6]
a[:3] == b[:3]

The above will yield a True if they match.如果它们匹配,上面将产生一个True

If you want to return the indexes of common elements between the two lists , there's a library called Numpy which has powerful features to do such jobs efficiently .如果要返回两个列表之间公共元素的索引,有一个名为 Numpy 的库,它具有强大的功能来高效地完成此类工作。

import numpy
a = [1, 2, 3, 4]
b = [0, 4, 6, 2]
_, c, d = numpy.intersect1d(a, b, return_indices=True)

This would return the following indexes:这将返回以下索引:

print(c)
print(d)
array([0, 1, 3]
array([0, 3, 1])

But the answer to your question:但你的问题的答案:

import random
import replit
import copy
import numpy
import time
number = 0
answer = 0
guesses = 0
x = 0
useranswer = []
generated = []
for i in range (0,4):
    num = random.randrange(1,9)
    generated.append(num)
replit.clear()
print("---------------------------------------------------------------------\nWelcome to MASTERMIND! you must guess the number that was generated!\n---------------------------------------------------------------------\n")
def useranswer_func():
    answer = str(input("Select a 4 digit number: "))
    if len(answer) != 4:
        print("Invalid answer type")
        time.sleep(9)  # The time provided by you is too much to wait!
        answer = ' '
    else:
        useranswer = list(answer)
        # You need to return values to use them outside the function.
        # Also your generated has int values but useranswer have str. So convert them to int or else they would never compare!
        return [int(i) for i in useranswer] 


if useranswer == generated:
      print("Good job! You became the MASTERMIND in one turn!")
else: 
    while useranswer != generated:
        # The returned values need to be stored in a variable.
        # Never use function name and variable name same. That could cause the error that you posted in the comment!
        useranswer = useranswer_func()
        guesses += 1
        if useranswer == generated:
            print("You have become the mastermind in " + str(guesses) + " tries!")
        else:
            c = []
            temp = copy.deepcopy(generated) # So that the change you make in temp is not reflected in generated variable too.
            for i in range(len(generated)):
                if generated[i] == useranswer[i]:
                    c.append(temp.index(temp[i]))
                temp[i] = None # If your generated has repeated values, the index returned will be different or else it would be always same.

            print("You got " + str(c) + " correct! ")

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

相关问题 Python:比较两个整数列表的最有效方法 - Python: Most efficient way to compare two lists of integers Python Pandas:在循环中比较两个列表的最有效方法是什么? - Python Pandas: What is the most efficient way to compare two lists in a loop? 在Python中相交列表最有效的方法? - Most efficient way to intersect list of lists in Python? 比较python中多个文件的最有效方法 - Most efficient way to compare multiple files in python Python - 比较两个字符串/列表中“正确”顺序排序的单词#的最有效方法 - Python - Most efficient way to compare # of words sequenced in “right” order across two strings/lists 压缩和比较Python列表的高效准确方法? - Efficient and accurate way to compact and compare Python lists? 在Python中比较3个列表的值的有效方法? - Efficient way to compare the values of 3 lists in Python? 根据列表的数值差异比较列表的最有效方法? - Most efficient way to compare lists based on their numerical differences? 在 Python 中将列表(列表列表)写入 csv 的最有效方法? - Most efficient way of writing a list (of lists of lists) to a csv in Python? 在python中删除多个列表中的几个项目的最有效方法? - Most efficient way to remove several items in several lists in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM