Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么不同的列表在同一个索引中?_Python_Python 3.x_List - Fatal编程技术网

Python 为什么不同的列表在同一个索引中?

Python 为什么不同的列表在同一个索引中?,python,python-3.x,list,Python,Python 3.x,List,当前,im编码用于计算幻方的一行元素数,并对其进行im测试-第一行有3个元素,第二行有4个元素,第三行有3个元素im尝试获取代码以确保所有行的元素数相同,但im显示输出: Enter filename :test [3] [4] [3] 我不确定当列表显示为这样向下时意味着什么,它们都在相同的索引0中 现行守则- r = input("Enter filename :") while True: try: f = open(r,"r") break

当前,im编码用于计算幻方的一行元素数,并对其进行im测试-第一行有3个元素,第二行有4个元素,第三行有3个元素im尝试获取代码以确保所有行的元素数相同,但im显示输出:

Enter filename :test
[3]
[4]
[3]
我不确定当列表显示为这样向下时意味着什么,它们都在相同的索引0中

现行守则-

r = input("Enter filename :")
while True:
    try:
        f = open(r,"r")
        break
    except:
        r = input("Enter the correct filename :")

while True: 
    line = f.readline()
    if not line:
        break
    a = line.split(' ')
    totalrow = len(a)
    m = []
    m.append(len(a))
    for x in m: 
        print(m[0])

我不知道如何将这些数字单独列在一个列表中,这样我就可以比较它们并应用验证了

您只需事先创建一个列表,遍历行并将行的长度附加到列表中即可。拆分到列表中

# Get the file.
r = input("Enter filename:")
while True:
    try:
        f = open(r, "r")
        break
    except FileNotFoundError:
        print(f"Could not locate a file named {r}.")
        r = input("Enter the correct filename: ")

# Count the rows for each line. 
elements_per_line = []
for line in f:  
    rows = len(line.split(" "))
    elements_per_line.append(rows)

# Do something with that information (`elements_per_line` == [2, 3, 2] now).
if sum(elements_per_line) != len(elements_per_line) * elements_per_line[0]:
    print("✗ Not all lines have the same size!")
else:
    print("✓ All lines have the same size.")

与问题无关,但为True:line=readline;如果不是行:请不要以这种方式迭代文件对象中的行。只需为f中的行执行:……老实说,我一点也不清楚您期望的是什么。请注意,在循环中,您对m:printm[0]中的x执行操作,因此始终只打印m中的第一个元素。。。但是,我也不知道你想做什么,告诉我们文件的内容。当然,m将始终有一个元素,因为你只在其中添加了一个元素。此外,您的代码不会在正在打印的数字周围产生方括号。同样,不清楚您试图做什么,以及您期望在要点之外得到什么结果,但是