相关疑难解决方法(0)

如何枚举从1开始的一系列数字

我使用的是Python 2.5,我想要一个像这样的枚举(从1开始而不是0):

[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]
Run Code Online (Sandbox Code Playgroud)

我知道在Python 2.6中你可以这样做:h = enumerate(range(2000,2005),1)给出上面的结果但是在python2.5中你不能......

使用python2.5:

>>> h = enumerate(range(2000, 2005))
>>> [x for x in h]
[(0, 2000), (1, 2001), (2, 2002), (3, 2003), (4, 2004)]
Run Code Online (Sandbox Code Playgroud)

有谁知道在python 2.5中获得所需结果的方法?

谢谢,

杰夫

python enums

130
推荐指数
8
解决办法
11万
查看次数

用行号 python 打印出(从文件中)每一行

我有一个.txt文档,其中包含一些单词,每个单词位于不同的行上。

例如:

hello
too
me
Run Code Online (Sandbox Code Playgroud)

我试图弄清楚如何打印每一行以及每个单词所在的行号,但从 1 开始,而不是 0 。

所需的输出:

1 = hello
2 = too
3 = me
Run Code Online (Sandbox Code Playgroud)

我已经有了一个从文本文档中获取行的解决方案:

open_file = open('something.txt', 'r')
lines = open_file.readlines()
for line in lines:
    line.strip()
    print(line)
open_file.close()
Run Code Online (Sandbox Code Playgroud)

我知道我可以打印出每个单词所在的索引,但是除非我弄错了,否则行号将从 0 而不是 1 开始。

python loops file list

2
推荐指数
1
解决办法
2万
查看次数

标签 统计

python ×2

enums ×1

file ×1

list ×1

loops ×1