[英]Python: Elegantly print all *remaining* elements from list in one line
I'm looking for the most correct way to print a list of elements after replacing one of them. 我正在寻找替换其中一个元素后打印元素列表的最正确方法。 I could do as follows but it's obviously messy.
我可以按照以下步骤进行操作,但这显然很混乱。
#!/usr/bin/python
import sys
file = open(sys.argv[1])
for line in file:
cols = line.split('\t')
if(float(cols[2]) > 97):
print line
else:
print cols[0] + "\tNo_Match\t" + cols[2] + "\t" + cols[3] + "\t" + cols[4] + "\t" + ..... + "\t" +cols[20]
EDIT: I just realised it would be even worse because I missed out the + "\\t" 编辑:我刚刚意识到那会更糟,因为我错过了+“ \\ t”
This gives identical behavior to the last line of your code: 这使代码的最后一行具有相同的行为:
print cols[0] + "\tNo_match\t" + ''.join(cols[2:])
To match the revised version of your code: 要匹配您的代码的修订版:
print cols[0] + "\tNo_match\t" + '\t'.join(cols[2:])
You could use the join
method of a string to print your list: 您可以使用字符串的
join
方法来打印列表:
cols[1] = "No_Match"
print '\t'.join(cols)
This will print off all entries of cols separated by a '\\t'. 这将打印出所有由'\\ t'分隔的cols条目。
Notice how I replaced the element 1 of cols first. 请注意,我是如何首先替换cols的元素1的。 If you don't want to do that, you can do either
如果您不想这样做,可以两者之一
print '\t'.join(cols[0:1]+['No_Match']+cols[2:])
or 要么
print '\t'.join([x if i != 1 else 'No_Match' for i, x in enumerate(cols)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.