从tab分隔的字符串创建列表

时间:2018-05-10 19:26:18

标签: python-3.x

我想从以下字符串创建一个列表,该列表保存在文件中:

neurovaultcols_050817   1073
neurovaultcols_050817   1606

这是代码:

repo_dataset=open("G:\\My Drive\\single.txt")
k=[]
for x in repo_dataset:           
    x.strip().strip("").split("\t")       
    k.append(x)
for b in k:
    print(b[0])

现在,当我使用print(b[0])时,我希望看到" aneurovaultcols_050817"。当我使用print(b[1])时,我想看到1073和1606。  但我只看到第一个字母:

n
n

我做错了什么?

1 个答案:

答案 0 :(得分:0)

更改为:

with open("G:\\My Drive\\single.txt", 'r') as f:
    k = [line.strip().split('\t') for line in f]

for b in k:
    print (b[0], b[1])

问题在于:

for x in repo_dataset:           
    x.strip().strip("").split("\t")       
    k.append(x)

基本上这是对你打开的文件(x)中的行(repo_dataset)说",剥离并拆分标签上的行"。这会返回一个列表,但您捕获它,然后将整行附加到k。如果我们将其分解:

for x in repo_dataset:
    # lets say 'x' is currently 'neurovaultcols_050817   1073'       
    x.strip().strip("").split("\t")
    # 'neurovaultcols_050817   1073'.strip() removes leading & trailing characters
    # 'neurovaultcols_050817   1073'.strip("") is not necessary
    # 'neurovaultcols_050817   1073'.split('\t') returns ['neurovaultcols_050817', '1073']
    #    but you don't store the list that gets returned so it does nothing essentially
    k.append(x)
    # k.append('neurovaultcols_050817   1073') is what happens

之后,这就是k的样子:

k = ['neurovaultcols_050817   1073', 'neurovaultcols_050817   1606']

因此for循环获得'neurovaultcols_050817 1073'作为第一个b。因此,对b[0]的调用代表字符串开头的'n'

更改对于您发布的原始代码非常简单(尽管我推荐我的代码):

repo_dataset=open("G:\\My Drive\\single.txt")
k=[]
for x in repo_dataset:           
    y = x.strip().split("\t") # change    
    k.append(y) # change
for b in k:
    print(b[0])