使用\ t在python中解析列表

时间:2015-07-31 18:47:00

标签: python string list parsing

我有一个文件,每行看起来像这样:

70.0010 1
70.0247 2
70.0248 1
71.0091 1
79.0152 1
79.0153 2

我想要的输出只有1 2 3 4 5,我该怎么做?感谢大家。

3 个答案:

答案 0 :(得分:3)

我同意Bhargav Rao的观点。使用for循环。

#include<stdio.h>
#include<string.h> 
int checkLucky(char *a); 
int main() 
{ 
char b[100]; 
int d; 
printf("Enter the input string\n"); 
gets(b); 
d=checkLucky(b); 
if(d==1) 
{ 
printf("%s is lucky\n",b); 
} 
else 
printf("%s is not lucky\n",b); 
return(0); 
} 
int checkLucky(char *a) 
{ 
int sum=0; 
while(*a!='\0') 
{ 
sum+=*a; 
a++; 
} 
if(sum%2==0) 
{ 
return(1); 
} 
else 
return(0);
}

我相信它会以你想要的方式打印出来。 否则请注明。

答案 1 :(得分:1)

If you are reading lines from a file, you can use the following approach:

with open("file.txt", "r") as f_input:
    for line in f_input:
        print line.replace("\t"," "),

If the file you are reading from is actually columns of data, then the following approach might be suitable:

import csv

with open("file.txt", "r") as f_input:
    csv_input = csv.reader(f_input, delimiter="\t")

    for cols in csv_input:
        print " ".join(cols)

cols would give you a list of columns for each row in the file, i.e. cols[0] would be the first column. You can then easily print them out with spaces as shown.

答案 2 :(得分:0)

有很多方法可以做到这一点。 您可以使用for循环,也可以只join列表并替换所有\t

a = ['1\t2\t3\t4\t5']

a = "".join(a).replace("\t", "")
print(a)