【搞懂python中的可迭代对象和迭代器对象(即迭代器)】教程文章相关的互联网学习教程文章

python-Cython是否提供任何合理简便有效的方法来迭代Numpy数组,就好像它们是平坦的一样?【代码】

假设我要实现Numpy的x[:] += 1在Cython.我可以写@cython.boundscheck(False) @cython.wraparoundcheck(False) def add1(np.ndarray[np.float32_t, ndim=1] x):cdef unsigned long ifor i in range(len(x)):x[i] += 1但是,这仅适用于ndim =1.我可以使用add1(x.reshape(-1))但这仅适用于连续的x. Cython是否提供任何合理简单有效的方法来迭代Numpy数组,就像它们是平坦的一样? (在Cython中重新实现此特定操作没有任何意义,因为上述Nu...

python-仅while循环的最后一次迭代保存【代码】

我有以下代码:symbolslist = ["100","200","300","400","500","600","700","800","900","1000","1500","2000","3000","4000","5000","7000","10000"]i=0 while i<len(symbolslist):htmltext = urllib.urlopen("http://www.fifacoinszone.com/default/quick/getpricedetail? platform_id=7&coins="+symbolslist[i] +"&cur=GBP")data = json.load(htmltext)pricelist = data["single_price_just"]print pricelist,i+=1输出:4.69 9....

Python在迭代时从列表中删除【代码】

我有一个字符串列表,我只想保留最独特的字符串.这是我的实现方式(循环可能有问题),def filter_descriptions(descriptions):MAX_SIMILAR_ALLOWED = 0.6 #40% unique and 60% similari = 0while i < len(descriptions):print("Processing {}/{}...".format(i + 1, len(descriptions)))desc_to_evaluate = descriptions[i]j = i + 1while j < len(descriptions):similarity_ratio = SequenceMatcher(None, desc_to_evaluate, descrip...

“只能迭代” Python错误【代码】

你好,我的程序员们. 我是一个相当新的程序员,现在我面临着巨大的困境.我收到错误消息:can only assign an iterable首先,我不知道那是什么意思. 其次,我将我的代码留给您的专业人员进行批判:def num_top(int_lis):duplic_int_lis = int_lisint_firs= duplic_int_lis [0]int_lis[:] = duplic_int_lis [int_firs]基本上,我试图在列表中找到[0]元素,然后将该int用作索引位置以在该索引位置找到整数.解决方法:int_lis [:] = duplic_i...

python-从__iter__返回一个非迭代器【代码】

class test(object):def __init__(self):passdef __iter__(self):return "my string"o = test() print iter(o)为什么这会提供追溯?$python iter_implement.py Traceback (most recent call last):File "iter_implement.py", line 9, in <module>print iter(o) TypeError: iter() returned non-iterator of type 'str'在这种情况下,我希望__iter__仅返回字符串.什么时候以及为什么检测到返回的对象不是迭代器对象?解决方法:可以通...

python-如何迭代Numpy数组的初始尺寸?【代码】

我有一个形状为[1000,1000,1000,3]的Numpy数组,是最后一个维度,大小为3,包含3D空间向量分量的三元组.如何使用nditer遍历每个三元组?像这样:for vec in np.nditer(my_array, op_flags=['writeonly', <???>]):vec = np.array(something)解决方法:我之前已经解决了这个问题,但这是一个简短的示例:vec=np.arange(2*2*2*3).reshape(2,2,2,3) it=np.ndindex(2,2,2) for i in it:print(vec[i])生产:[0 1 2] [3 4 5] [6 7 8] [ 9 10 11...

在python中的迭代器/生成器中异常提升后继续【代码】

Python中是否有任何方法可以在迭代器/生成器抛出异常后继续迭代?就像下面的代码一样,有没有办法跳过ZeroDivisionError并继续循环遍历gener()而不用modyfying run()函数?def gener():a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]for i in a:yield 2/idef run():for i in gener():print i#---- run script ----#try:run() except ZeroDivisionError:print 'what magick should i put here?'解决方法:try / except的逻辑位置是发生违规计算的地...

如何创建python迭代器的副本?【代码】

参见英文答案 > How to clone a Python generator object? 5个在python中我尝试使用赋值创建我的迭代器的副本,但是它创建了一个迭代器的副本,它引用了原始迭代器本身.例如:my_list = [5, 4, 3,2] first_it = iter(my_list) second_it = first_it print next(first_it ) #it will print 5 print next(second_it) #it will print 4 print next(first_it ) #it will print...

Python和Pygame:在迭代期间更新循环中列表中的所有元素【代码】

我正在使用Python并使用Pygame编写程序.这是基本代码的样子:while 1:screen.blit(background, (0,0))for event in pygame.event.get():if event.type == QUIT:pygame.quit()sys.exit()if event.type == KEYDOWN and event.key == K_c:circle_create = Truecircle_list.append(Circle())if event.type == MOUSEBUTTONDOWN and circle_create == True:if clicks == 0:circle_list[i].center()clicks += 1if event.type == MOUSEMOTI...

(Python)列表索引超出范围 – 迭代【代码】

参见英文答案 > python : list index out of range error 9个> How to remove items from a list while iterating? 26个 for i in range(len(lst)): if lst[i][0]==1 or lst[i][1]==1:lst.remove(lst[i]) return lst这给出了“IndexError:list index超出范围”为什么会发生这种情况?解决方法:你正在修改你正在迭代的列表.如果你这样做,列表...

在Python中的迭代器之间交替【代码】

参见英文答案 > How do I merge two python iterators? 13个替换Python中不同迭代器的值的最有效方法是什么,例如,alternate(xrange(1,7,2),xrange(2,8,2))将产生1,2,3, 4,5,6.我知道实现它的一种方法是:def alternate(*iters):while True:for i in iters:try:yield i.next()except StopIteration:pass但是有更高效或更清洁的方式吗? (或者,更好的是,我错过了一个itertools函数?)解决方法:拉...

如何在python 3中从for inside for循环中增加迭代器?【代码】

for i in range (0, 81):output = send commandwhile True:last_byte = last_byte - offsetif last_byte > offset:output = send commandi+else:output = send commandi+break我想在每次执行send命令时增加迭代器.现在它只在执行for循环时增加1.请指教for i in range(0,10):print(i)i +=2print("increased i", i)我运行了这段代码,它从0到9生成.我原以为它会将迭代器增加2.解决方法:将迭代器的副本保存为命名对象.然后,如果你愿意,...

如何在Python中迭代cur.fetchall()【代码】

我正在使用Python 3.4中的数据库连接.我的数据库中有两列. 下面是查询,它以所示格式显示来自两列的所有数据查询:cur.execute(""" select * from filehash """) data=cur.fetchall() print(data)OUTPUT:[('F:\\test1.py', '12345abc'), ('F:\\test2.py', 'avcr123')]要遍历此输出,我的代码如下所示cur.execute(""" select * from filehash """) data=cur.fetchall()i=0 j=1for i,row in data:print(row[i])print(row[j])i=i+1这给...

在Python中按排序顺序从排序的迭代器中产生?【代码】

是否有更好的方法将一堆已排序的迭代器合并/整理成一个,以便按排序顺序生成项目?我认为下面的代码可以工作,但我觉得有一种更清晰,更简洁的方法,我错过了.def sortIters(*iterables, **kwargs):key = kwargs.get('key', lambda x : x)nextElems = {}currentKey = Nonefor g in iterables:try:nextElems[g] = g.next()k = key(nextElems[g])if currentKey is None or k < currentKey:currentKey = kexcept StopIteration:pass #iter...

python – 迭代dict值【代码】

如果我想迭代存储在元组中的字典值. 我需要返回保存“CI”值的对象,我假设我需要某种for循环:z = {'x':(123,SE,2,1),'z':(124,CI,1,1)} for i, k in db.z:for k in db.z[i]:if k == 'CI':return db.z[k]我可能在这里遗漏了一些东西,一个参考点会很好. 如果有更快的方式,那么这一切都会有很大的帮助解决方法: z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)} for i in z.keys(): #reaching the keys of dictfor x in z[i]: #reaching...