我发现自己需要借助for循环来遍历列表。我最终要做的是这样:
L = ['A','B','C','D']
n = 0
for i in L:
print(L[n])
n += 1
我想知道是否有更好的方法来执行此操作,而不必每次都声明一个额外的变量n
?
请记住,这只是一个简化的示例。这样的解决方案是不够的(尽管在本示例中结果是相同的):
L = ['A','B','C','D']
for i in L:
print(i)
答案 0 :(得分:5)
使用enumerate:
SELECT CASE WHEN rn = 1 THEN pn END prog_name,
st_name,
loan,
LOCATION,
weeks
FROM (SELECT prog_name pn,
st_name,
sum(loan) loan,
LOCATION,
sum(weeks) weeks,
row_number() OVER (PARTITION BY prog_name ORDER BY st_name, weeks, LOCATION) rn
FROM your_results
GROUP BY GROUPING SETS ((prog_name, st_name, loan, location, weeks), (prog_name), ()))
ORDER BY pn, st_name, weeks, LOCATION;
答案 1 :(得分:5)
来自docs:
在Python中,enumerate()函数用于遍历列表 同时跟踪列表项的索引。
使用enumerate()
:
L = ['A','B','C','D']
for index, element in enumerate(L):
print("{} : {}".format(index,element)) # print(index, L[index])
输出:
0 : A
1 : B
2 : C
3 : D