Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.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_Numpy - Fatal编程技术网

Python 把线分成几列

Python 把线分成几列,python,numpy,Python,Numpy,我有一个这样的文件(以空行结尾) 使用numpy或其他方法是否有更好或更短的方法执行此操作?您可以split并使用1的第二个参数仅分割1次 with open('file.txt', 'r') as f: d = {} for line in f: if line.strip(): value, key = line.split(' ',1) d[key] = int(value) 把它简化成听写理解 with o

我有一个这样的文件(以空行结尾)


使用numpy或其他方法是否有更好或更短的方法执行此操作?

您可以
split
并使用
1
的第二个参数仅分割1次

with open('file.txt', 'r') as f:
    d = {}
    for line in f:
        if line.strip():
            value, key = line.split(' ',1)
            d[key] = int(value)
把它简化成听写理解

with open('file.txt', 'r') as f:
    d = {key:int(value) for value,key in [line.split(' ',1) for line in f if line.split()]}

您可以
split
并使用
1
的第二个参数仅拆分1次

with open('file.txt', 'r') as f:
    d = {}
    for line in f:
        if line.strip():
            value, key = line.split(' ',1)
            d[key] = int(value)
把它简化成听写理解

with open('file.txt', 'r') as f:
    d = {key:int(value) for value,key in [line.split(' ',1) for line in f if line.split()]}

我能得到的最短的,应该足够有效,但有点神秘:)


我能得到的最短的,应该足够有效,但有点神秘:)


这不会处理
hello hello
对吧?它也不会处理空行这不会处理
hello hello
对吧?它也不会处理空行
d = {}
with open('file2.txt') as f:
    for l in f:
        s = l.split(' ')
        d[s[1]] = s[0]  
        print d
with open('file.txt', 'r') as f:
    rows = map(lambda l: l.strip().partition(' '), f)
    d = { r[2]: int(r[0]) for r in rows if r[2] }