从inpu上的列表中获取最近的元素

2024-09-27 00:13:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,其中包含一些类似于猜测数字的游戏,其中第一列只是一个唯一的id,第二列和第三列是gues的范围,第四列是一个组类型:

a:6.5:10.2:G1
b:2.4:11.7:G2
c:3.1:9.7:G1
d:4.6:8.7:G3

用户将被提示输入两次,例如:

3.1 : 9.9 : 3.2 : 9.8

其中前两次是第一次尝试,第三次和第四次是第二次尝试。根据上面的输入,代码将第一次尝试和第二次尝试与文本文件中的内容进行比较。你知道吗

示例:

第一次尝试将是3.1:9.9,并继续与文本文件中的内容进行比较。还将比较第二次尝试3.2:9.8,并产生与用户输入最接近的输出,即:

output = 3.1 , 9.7 (from the text file, without the id and type)

这是我试过的。首先,我创建了两个列表,因为文件中每行只有两组数字,而用户有四组数字,我认为如果我把输入分成两组,每个数字都放在一个列表中进行比较会很方便。你知道吗

guess = input("Enter your guess:")  #Ex: 3.1:9.9:3.2:9.8
List1 = []                          # [3.1,9.9]
List2 = []                          # [3.2,9.8]
separateStr = guess.split(':')
floatInput = [float(i) for i in separateStr]

List1,List2 = floatInput[:2],floatInput[2:]

openFile = open('__.txt')
table = []                  #Created a list to contain the contents
for line in openFile:
    contents = line.strip().split(':')
    table.append(contents)

def getClosest(l):
    for i in range(....
    .
    .

我无法计算出最近范围的函数,因为我假设如果两个列表能够与包含文件内容的表进行比较,是否可能?我的方法可能是错误的,所以我想为此寻求建议。你知道吗


Tags: 文件the用户inid内容列表for
1条回答
网友
1楼 · 发布于 2024-09-27 00:13:16

我没有测试它,因为我是懒惰的自动取款机,但它应该是好的。你知道吗

def get_closest(test, my_table):
    min_dist = 10e5
    pos = None
    for i, data in enumerate(my_table):
        dist = ((test[0] - data[0])**2 + (test[1] - data[1])**2)**0.5  # euclidean norm
        if dist < min_dist:
            pos = (i, data)
            min_dist = dist
    return pos

openFile = open('__.txt')
table = []
for line in openFile:
    table.append(line.strip().split(':')[1:3])  # only the numbers

user_input = input("Enter your guess:")  # Ex: 3.1:9.9:3.2:9.8
floatInput = list(map(float, user_input.split(':')))
guesses = [floatInput[:2], floatInput[2:]]
for guess in guesses:
    winner = get_closest(guess, table)
    print(winner[1])

注意事项:

  • 用户输入的格式很奇怪。我会使用更直观的方法,比如3.1,9.9;3.2,9.8(区分中间分隔符和休息分隔符)

相关问题 更多 >

    热门问题