首页 > 解决方案 > python从多个列表中旋转选择

问题描述

我有 4 个列表如下:

import numpy as np

file1 = np.arange(0, 4).tolist()
file2 = np.arange(3, 7).tolist()
file3 = np.arange(7, 11).tolist()
file4 = np.arange(11, 15).tolist()

我想从每个列表中轮流选择,最终得到如下一组:

final = {0, 4, 9, 14}

我有一个可行的解决方案,但我想知道是否有更简单的方法或更pythonic的方法来做到这一点?

def get_rotated(file1: list,
                         file2: list,
                         file3: list,
                         file4: list):
    count = 0
    i = 0    
    final = set()    
    while i < (get_len(file1) -1):
        print('here')
        if count == 0:
            print(i)
            tag = file1[i]
            count+=1
            final.add(tag)
            i += 1
        if count == 1:
            print(i)

            tag = file2[i]
            count+=1
            final.add(tag)
            i += 1
        if count == 2:
            print(i)
            tag = file3[i]
            count+=1
            final.add(tag)
            i += 1    
        if count == 3:
            print(i)
            tag = file4[i]
            count=0
            final.add(tag)
            i += 1
    return final

这将返回正确的集合 {0, 4, 9, 14}。如果列表大小更大,我希望这可以继续分组旋转选择。

标签: pythonlistindexing

解决方案


这就是你需要的。您应该通过迭代使用如下列表名称

import numpy as np

file1 = np.arange(0, 4).tolist()
file2 = np.arange(3, 7).tolist()
file3 = np.arange(7, 11).tolist()
file4 = np.arange(11, 15).tolist()

countOfLists = 4
finalList = []
for i in range(1, countOfLists + 1):
    finalList.append(globals()['file%s'%i][i - 1])
print(finalList)

推荐阅读