Python:将值列表分成 x 个部分,并为 x 中的每个值赋予一个变量

Python: separate list of values into x number of sections, and give each value in x a variable

我有一个数字列表 [1, 2, 3, 4, 5, 6, 7, 8]、一个颜色列表 ['red', 'green', 'orange', 'blue'] 和一个变量 chunks。根据块的值,我将 return 每个数字与一种颜色相关联。

例如:chunks = 2 将 return 两个值的颜色

1 - red
2 - red
3 - green
4 - green
5 - orange
6 - orange
7 - blue
8 - blue

chunks = 4 将 return 四个值的颜色

1 - red
2 - red
3 - red
4 - red
5 - green
6 - green
7 - green
8 - green

如何遍历此列表以吐出我需要的内容?

试试这个

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
colors = ['red', 'green', 'orange', 'blue']
chunkedColors = sorted(colors*(len(numbers)//chunks),key=colors.index)[:len(numbers)]

使用一些索引技巧:

>>> nums = [1, 2, 3, 4, 5, 6, 7, 8]
>>> colors = ['red', 'green', 'orange', 'blue']
>>> chunks = 4
>>> for i,num in enumerate(nums):
    print("%s:%s"%(num,colors[i*chunks//len(nums)%len(colors)]))
1:red
2:red
3:green
4:green
5:orange
6:orange
7:blue
8:blue

主要部分是 colors[i*chunks//len(nums)%len(colors)],可以这样分解:

colors[i*chunks//len(nums)%len(colors)]
       ^                              index of num in nums
        ^      ^                      multiply by chunks then later dividing by len is the
                                      same as dividing by len/chunks
               ^                      explicit integer divide is important for indexing
                          ^           ensures that there is no index error if 
                                      chunks>len(colors) (check example)

chunks 的高值示例:

>>> chunks = 7
>>> for i,num in enumerate(nums):
    print("%s:%s"%(num,colors[i*chunks//len(nums)%len(colors)]))


1:red
2:red
3:green
4:orange
5:blue
6:red
7:green
8:orange