相关疑难解决方法(0)

在'for'循环中访问索引?

如何访问索引本身以获取如下列表?

ints = [8, 23, 45, 12, 78]
for i in ints:
    print('item #{} = {}'.format(???, i))
Run Code Online (Sandbox Code Playgroud)

当我使用循环遍历它时for,如何访问循环索引,在这种情况下从1到5?

python loops list

3312
推荐指数
22
解决办法
194万
查看次数

最优雅的方法来修改嵌套列表的元素

我有一个2D列表,如下所示:

table = [['donkey', '2', '1', '0'], ['goat', '5', '3', '2']]
Run Code Online (Sandbox Code Playgroud)

我想将最后三个元素更改为整数,但下面的代码感觉非常难看:

for row in table:
    for i in range(len(row)-1):
        row[i+1] = int(row[i+1])
Run Code Online (Sandbox Code Playgroud)

但我宁愿有一些看起来像:

for row in table:
    for col in row[1:]:
        col = int(col)
Run Code Online (Sandbox Code Playgroud)

我认为应该有一种方法来编写上面的代码,但是切片创建了一个与原始代码分开的迭代器/新列表,因此引用不会延续.

有没有办法获得更多的Pythonic解决方案?

python nested-lists

28
推荐指数
3
解决办法
4万
查看次数

只需要索引:枚举或(x)范围?

如果我只想在循环中使用索引,我应该更好地range/xrange结合使用该函数len()

a = [1,2,3]
for i in xrange(len(a)):
    print i 
Run Code Online (Sandbox Code Playgroud)

还是enumerate?即使我根本不使用p

for i,p in enumerate(a):
    print i    
Run Code Online (Sandbox Code Playgroud)

python enumerate range

28
推荐指数
3
解决办法
9322
查看次数

Python范围len vs枚举

I read from range(len(list)) or enumerate(list)? that using range(len(s)) is not very good way to write Python. How one can write for loops in alternative way if we do not need to loop len(s) times but for example len(s)//3 times or len(s)-5 times? Is it possible to convert those loops to use enumerate?

For example, I had a project where I had a list of 3n elements 's[0], s[1],...,s[3n-1]' and I needed to print them in a nx3 table. …

python python-3.x

3
推荐指数
1
解决办法
3747
查看次数

标签 统计

python ×4

enumerate ×1

list ×1

loops ×1

nested-lists ×1

python-3.x ×1

range ×1