在接收列表时,如何将参数限制为特定的数字?

2024-04-20 04:44:56 发布

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

def is_triangle (a,b,c):
    if (a + b) >= c and  (c + b) >= a and (b+c) >= a:
        return 1
    else:
        return 0 

tri = open('triangles.txt','r')
tri_2 = tri.readlines()
input_numbers = list(map(lambda i: int, tri_2))
ans_list = []
result = is_triangle (*input_numbers)
ans_list.append(result)
print(" ")
print(*ans_list, sep = " ")

程序的目标是从文本文件中获取一个列表,并从函数is_triangle返回1或0,1表示它是三角形,0表示它不是三角形。 我的代码可能还有其他问题。但是主要的问题是我收到了消息TypeError: is_triangle() takes 3 positional arguments but 25 were given.,所以我意识到参数包含了太多的参数。我想知道是否有办法限制列表中参数的数量。你知道吗

403 203 586
794 919 542
510 924 453
258 116 158
1316 2613 671
721 369 1725
493 929 1177
747 606 834

我意识到的另一件事是文本文件正在列表中创建一个列表。你知道吗


Tags: and列表input参数returnisresulttri
3条回答

如果你把你的is_triangle改成一个列表,然后把它解包,你就可以把你的文件读入一个列表列表,把那些子列表转换成ints,然后把每个子列表也就是[403, 203, 586]传递到is_triangle

def is_tri(x):
    a, b, c = x
    if (a + b) >= c and  (c + b) >= a and (b+c) >= a:
        return 1
    else:
        return 0

with open('triangles.txt') as f:
    content = [line.split() for line in f]

content = [list(map(int, i)) for i in content]
ans_list = [is_tri(i) for i in content]
print(' ')
print(*ans_list, sep = ' ')
#
# 1 1 1 1 1 0 1 1

逐行读取和处理:

with open('triangles.txt','r') as infile:
    for line in infile:
        ...

让我们来看看这些方面发生了什么:

tri = open('triangles.txt','r')
tri_2 = tri.readlines()

如果您检查tri_2中的内容,应该会看到如下内容:

tri_2[0] = "403 203 586"
tri_2[1] = "794 919 542"
…

这意味着tri_2的大小将为25(或者不管文件中有多少行),使得input_numbers也有25个条目,然后将25个参数传递给is_triangle。你知道吗

正如其他人所指出的,您应该逐行进行,从每行中提取数字,然后调用is_triangle。它应该类似于:

...
ans_line = []
for line in tri_2:
    split_line = line.split()
    input_numbers = map(int, split_line)
    result = is_triangle(*input_numbers)
    ans_line.append(result)
...

相关问题 更多 >