Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个包含两列的 .txt 文件。如果第一列中的值符合我的条件,那么我想存储第二列的值。这是我迄今为止所拥有的,但将它存储两次似乎很愚蠢。任何更好的方法将不胜感激。
file = open(nameoffile.txt, 'r') for line in file.readlines(): if (line.startswith("something")): value = line.split() P_point = value[1]
不太确定“存储两次”,但你的代码最好写成:
with open('somefile') as fin: points = [line.split()[1] for line in fin if line.startswith('something')]