Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.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中的for循环_Python_Loops_For Loop - Fatal编程技术网

python中的for循环

python中的for循环,python,loops,for-loop,Python,Loops,For Loop,这是我在文本文件中的不同行中获取数据的方式,如 inFile = open("subjects.txt","r") global subArray subArray = [] global line for line in inFile: subArray.append(line) inFile.close() return subArray 我需要知道当数据在一行中时如何做 math science

这是我在文本文件中的不同行中获取数据的方式,如

    inFile = open("subjects.txt","r") 
    global subArray 
    subArray = [] 
    global line 
    for line in inFile: 
            subArray.append(line) 
    inFile.close() 
    return subArray
我需要知道当数据在一行中时如何做

math
science
art

line.split,将字符串转换为字符串列表的数组。您还可以查看标准csv模块。

line.split将字符串转换为字符串列表的数组。您还可以查看标准的csv模块。

如果整个文件仅为一行,则该模块将起作用:

math , science , geography
或者,如果要在循环中执行此操作:

subArray = [subj.strip() for subj in open("subjects.txt","r").read().split(',')]
或使用csv模块:

 inFile = open("subjects.txt","r")
 subArray = []
 for line in inFile
    for subject in line.split(','):
        subArray.append(subject.strip())
 return subArray

如果整个文件仅为一行,则此操作有效:

math , science , geography
或者,如果要在循环中执行此操作:

subArray = [subj.strip() for subj in open("subjects.txt","r").read().split(',')]
或使用csv模块:

 inFile = open("subjects.txt","r")
 subArray = []
 for line in inFile
    for subject in line.split(','):
        subArray.append(subject.strip())
 return subArray

No.line.split,将字符串转换为字符串列表。Python中没有数组,除了模块数组中特殊的对象。@eyquem:是的,当然你是对的。我只是在用OP的语言。编辑。谢谢No.line.split,将字符串转换为字符串列表。Python中没有数组,除了模块数组中特殊的对象。@eyquem:是的,当然你是对的。我只是在用OP的语言。编辑。谢谢名称子数组是不明确的,因为在Python中列表不是数组,而是列表。数组是模块数组的一个类,用于创建元素同质的对象。子数组的名称不明确,因为在Python中列表不是数组,而是列表。数组是模块数组的一类,用于创建元素同质的对象。