2017-07-30 78 views
0

我想在此處詢問關於python的內容。我在這種編程是新將文件txt讀入列表2 Python中的維度

輸入:

Emma,F,19414 
Olivia,F,19246 
Ava,F,16237 

輸出:

[['Emma', 'F', '19414'], 
['Olivia', 'F', '19246'], 
['Ava', 'F', '16237']] 

所以,這就是我想要得到的工作。這是一個二維表,所以我可以訪問它的值是「F」第1排在theList[0][1]

+1

您是如何給出意見的?它是一個普通的字符串作爲輸入?或者你的輸入是從文件中讀取的? – Haranadh

+1

你的程序代碼在哪裏? –

+0

你好,歡迎來到Stack Overflow,請花點時間瀏覽[歡迎導覽](https://stackoverflow.com/tour),瞭解你在這裏的方式(並獲得你的第一張徽章),閱讀如何創建一個[mcve]示例並檢查[問],以便增加獲得反饋和有用答案的機會。 – garfbradaz

回答

0

f.txt:

Emma,F,19414 
Olivia,F,19246 
Ava,F,16237 
Emma,DF,19414 
Olivia,D,19246 

代碼:

with open("path/to/f.txt", "r") as fp: 
    f_content = fp.read().strip() # read lines and strip whitespaces 
print([x for x in [i.split(',') for i in f_content.split("\n")] if x[1] =="F"]) # prints only list if column is F 
0

如果輸入是一個簡單的多行字符串列,讓我們接着說:

s_input = """Emma,F,19414 
Olivia,F,19246 
Ava,F,16237""" 

theList = [ each.split(",") for each in s_input.splitlines() ] 
print theList 

for i, _ in enumerate(theList): 
    print theList[i][1] 

輸出可:

[['Emma', 'F', '19414'], ['Olivia', 'F', '19246'], ['Ava', 'F', '16237']] 
F 
F 
F 
+0

謝謝so muchhhhhh –

+0

@ANJAYCHANNEL,歡迎光臨。如果你喜歡答案,請註冊。 – Haranadh

0

你可以試試這個方法:

infile.txt

Emma,F,19414 
Olivia,F,19246 
Ava,F,16237 

代碼:

list_of_lists = [] 
with open('infile.txt') as f: 
    for line in f: 
    inner_list = [elt.strip() for elt in line.split(',')] 
    # in alternative, if you need to use the file content as numbers 
    # inner_list = [int(elt.strip()) for elt in line.split(',')] 
    list_of_lists.append(inner_list) 

print(list_of_lists) 

輸出:

[['Emma', 'F', '19414'], ['Olivia', 'F', '19246'], ['Ava', 'F', '16237']] 
+0

謝謝你這麼多 –

+0

@ANJAY。歡迎。 :) –