为python中的每一行编号

时间:2018-06-23 12:08:36

标签: python python-3.x

在我的以下脚本中

atind=[5,37,43,55,75,85,104,127,141,147,168,182,197,203,213,235,245,269,288,307,331,352,372,393,407,417,439,449,456,475,485,502,516,536,552,573,580,587,597,621,631,653,677,691,705,725,747,758,768,783,795,805,822,846,860,870,877,884]
for f in feat.describe_features(ds[0]):
    [a,b]=f['resseqs']
    print("d: DISTANCE ATOMS=%d,%d"%(atind[a-1], atind[b-1]))

我得到类似

的输出
d: DISTANCE ATOMS=85,141
d: DISTANCE ATOMS=85,147
d: DISTANCE ATOMS=85,168
d: DISTANCE ATOMS=85,182
d: DISTANCE ATOMS=85,197
d: DISTANCE ATOMS=85,203
d: DISTANCE ATOMS=85,213

....有超过1000行这样的内容,我想要的是一种方法,这样我就可以编辑脚本以对输出进行编号

d1: DISTANCE ATOMS=85,141
d2: DISTANCE ATOMS=85,147
d3: DISTANCE ATOMS=85,168
d4: DISTANCE ATOMS=85,182
d5: DISTANCE ATOMS=85,197
d6: DISTANCE ATOMS=85,203
d7: DISTANCE ATOMS=85,213

...直到最后一个。

任何很棒的技巧都可以做到这一点。我可以用bash来做,但是这太繁琐了。我想我缺少非常基本的Python方法。任何帮助将不胜感激。

我想应该是d$i之后的变量,也许不是吗?

2 个答案:

答案 0 :(得分:7)

使用enumerate作为迭代器以产生索引值对:

for i, f in enumerate(feat.describe_features(ds[0]), start=1):
    [a,b]=f['resseqs']
    print("d%d: DISTANCE ATOMS=%d,%d"%(i, atind[a-1], atind[b-1]))

如果使用Python 3.6+,还请注意,您可以使用 f-string 获得更好的格式:

for i, f in enumerate(feat.describe_features(ds[0]), start=1):
    a, b = f['resseqs']
    print(f"d{i}: DISTANCE ATOMS={atind[a - 1]},{atind[b - 1]}")

答案 1 :(得分:1)

您可以使用以下内容:

list = [ "abc", "def" , "mno"]
for i,c in enumerate(list):
    print i,c