如何访问索引本身以获取如下列表?
ints = [8, 23, 45, 12, 78]
for i in ints:
print('item #{} = {}'.format(???, i))
Run Code Online (Sandbox Code Playgroud)
当我使用循环遍历它时for,如何访问循环索引,在这种情况下从1到5?
现在我正在循环跟踪我的索引
index = 0
for entry in longList:
if entry == 'foo':
print index
index += 1
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
我试图读取txt文件的每一行,并打印出不同文件中的每一行.假设,我有一个文本如下:
How are you? I am good.
Wow, that's great.
This is a text file.
......
Run Code Online (Sandbox Code Playgroud)
现在,我希望filename1.txt有以下内容:
How are you? I am good.
Run Code Online (Sandbox Code Playgroud)
filename2.txt 具有:
Wow, that's great.
Run Code Online (Sandbox Code Playgroud)
等等.
我的代码是:
#! /usr/bin/Python
for i in range(1,4): // this range should increase with number of lines
with open('testdata.txt', 'r') as input:
with open('filename%i.txt' %i, 'w') as output:
for line in input:
output.write(line)
Run Code Online (Sandbox Code Playgroud)
我得到的是,所有文件都包含文件的所有行.我希望每个文件只有1行,如上所述.
我有时使用生成器来过滤程序中的某些值,并希望记录过滤的项目.
我们假设:
def filter_items(items):
for item in items:
if item.is_wanted():
yield item
def process_items(items):
for item in filter_items(items):
item.do_stuff()
Run Code Online (Sandbox Code Playgroud)
现在我的问题是我想记录,实际调用了多少过滤的项目.
目前我这样做:
def process_items(items):
for count, item in enumerate(filter_items(items)):
item.do_stuff()
try:
count += 1
except UnboundLocalError:
count = 0
print('Processed', count, 'items.')
Run Code Online (Sandbox Code Playgroud)
现在我有这样的感觉,检查UnboundLocalError一个有点奇怪,所以我考虑默认计数器:
def process_items(items):
count = -1
for count, item in enumerate(filter_items(items)):
item.do_stuff()
print('Processed', count + 1, 'items.')
Run Code Online (Sandbox Code Playgroud)
然而,设置默认计数器-1也看起来很奇怪,因为没有迭代的实际默认值将是0.但是我不能默认它,0因为我无法区分默认值(如果没有迭代元素)或者是否迭代了一个元素.
有关Python中循环计数器默认的最佳实践或指南吗?