(重复)获取要在lis中的前x个元组上执行的循环

2024-10-04 01:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很长的元组列表,例如[1,2)、(18485)、(284475)…]。我还有一个for循环,它将对这些元组的组执行一个函数。我希望在前68个元组上执行循环,然后在下68个元组上执行循环,然后在下68个元组上执行循环,依此类推,直到对所有元组执行循环为止(顺便说一下,元组的总数可以被68整除)

我想先将元组分组到68个单独的列表中,然后想知道使用“in range(68)”函数是否更有效?我只是不知道如何让for循环转到下一组68个元组,而不重新读取前68个元组

我还没有太多的代码,只是


    tuple1= new_tuple # changing tuple of tuples to list of tuples
    list_of_tuples = list(tuple1)


   # here I want to either split the list into mini-lists of 68, or start the for loop for the first 68 tuples, then the next 68 etc. 

    #the for loop:
      for z in SOMETHING?
      d = z
      mdata = []

      for p, k in combinations(d,2): 
        distance = math.sqrt( ((p[0]-k[0])**2)+((p[1]-k[1])**2) )
        mdata.append(distance)

不过我觉得这帮不了什么忙。非常感谢任何帮助,甚至只是建议。提前谢谢


Tags: oftheto函数inloop列表for
1条回答
网友
1楼 · 发布于 2024-10-04 01:29:57

使用列表切片

list_of_tuples = list(...)

# start at position 0
start = 0

# grab 68 items each time
chunk = 68

# keep going while there are more items left
while start <= len(list_of_tuples):

    # process each item in the current slice
    for z in list_of_tuples[start:start+chunk]
        # process z...

    # advance to the next 68 items
    start += chunk

相关问题 更多 >