在Python中,如何将列表中的非连续值插入到字典的特定键中?

qyswt5oh  于 2023-05-21  发布在  Python
关注(0)|答案(3)|浏览(107)

Python -将列表值添加到字典中,但确保它们不连续
你好。我有一个名单,说:
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
我也有一个字典,有3个空列表的键,比如:

sample = {
    "A": [],
    "B": [],
    "C": [],
}

我需要将列表的值插入到字典的值中,但要确保每个键只有4个值,并且它们不能连续。
例如,这是正确的,因为每个键有4个值,并且没有一个是连续的:

sample = {
    "A": [1, 3, 5, 7],
    "B": [2, 10, 12, 8],
    "C": [4, 11, 9, 6],
}

这些值可以是随机的(也就是说,它们不需要按升序/降序排列),但它们必须来自列表。有人能帮帮我吗?
这是我目前所知道的它将值插入到列表中,但这些值都是连续的。

`overs = []

# Creates a list with values from 1 to 12
for i in range(1, 13):
    overs.append(i)

print(overs)

players = {"A": [], "B": [], "C": []}

# Creates a dictionary where the values of the list are inserted into the values of the dictionary

for player in players:
    for i in range(1, 13):
        try:
            if len(players[player]) < 4:
                players[player].append(overs[0])
                overs.pop(0)

        except IndexError:
            break

print(players)`
Output : 

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
{'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8], 'C': [9, 10, 11, 12]}
ygya80vv

ygya80vv1#

在做一些更复杂的事情之前,我会简单地将第一个项目放在第一个桶中,下一个放在下一个桶中,使用模运算符进行 Package 。

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
sample = {"A": [], "B": [], "C": []}
values = list(sample.values())
values_len = len(values)

for index, item in enumerate(l):
    values[index % values_len].append(item)

print(sample)

这将为您提供:

{'A': [1, 4, 7, 10], 'B': [2, 5, 8, 11], 'C': [3, 6, 9, 12]}

(每一次)

jexiocij

jexiocij2#

创建具有3个键和4个不连续值的字典

# Creates a list with values from 1 to 12
overs = list(range(1, 13))
print(overs)

# Creates a dictionary where the values of the list are inserted into the values of the dictionary
players = {"A": [], "B": [], "C": []}
for player in players:
    prev_value = None  # Store the previous value for each player
    while len(players[player]) < 4 and overs:  # Stop when the list is empty or the player's list has 4 elements
        current_value = overs.pop(0)  # Take the first value from the list
        if prev_value is not None and abs(current_value - prev_value) == 1:  # Check for consecutive values
            overs.append(current_value)  # Reinsert the consecutive value back to the list
        else:
            players[player].append(current_value)
            prev_value = current_value

print(players)
5vf7fwbs

5vf7fwbs3#

如果你想让分布更随机,你也可以试试这个:

import random

sample = {
    "A": [],
    "B": [],
    "C": [],
}

l = [i+1 for i in range(12)]
samples = len(sample)

for i in range(0, len(l), samples):           # iterate over sample in steps of 3 (number of keys)
    order = random.sample(list(sample.keys()), samples)  # shuffle order in which keys appear
    for key, item in zip(order, l[i:i+samples]):         # add numbers sequentially to shuffled keys
        sample[key].append(item)
        
print(sample)

样本输出:

{
'A': [2, 5, 9, 10],
'B': [1, 6, 7, 12], 
'C': [3, 4, 8, 11]
}

相关问题