从列表中随机选择值但具有字符长度限制

Jac*_*tad 8 python

我有两个字符串列表,如下所示:

test1 = ["abc", "abcdef", "abcedfhi"]

test2 = ["The", "silver", "proposes", "the", "blushing", "number", "burst", "explores", "the", "fast", "iron", "impossible"]
Run Code Online (Sandbox Code Playgroud)

第二个列表更长,所以我想通过随机抽样将其下采样到第一个列表的长度.

def downsample(data):
    min_len = min(len(x) for x in data)
    return [random.sample(x, min_len) for x in data]

downsample([list1, list2])
Run Code Online (Sandbox Code Playgroud)

但是,我想添加一个限制,即从第二个列表中选择的单词必须与第一个列表的长度分布相匹配.因此,对于随机选择的第一个单词,它必须与较短列表的第一个单词具有相同的长度.这里的问题是也不允许替换.

如何随机选择n(短列表的长度)元素,test2从中匹配字符长度分布test1?谢谢,杰克

use*_*203 7

建立

from collections import defaultdict
import random
dct = defaultdict(list)
l1 = ["abc", "abcdef", "abcedfhi"]
l2 = ["The", "silver", "proposes", "the", "blushing", "number", "burst", "explores", "the", "fast", "iron", "impossible"]
Run Code Online (Sandbox Code Playgroud)

首先,用于collections.defaultdict创建一个字典,其中键是字长:

for word in l2:
  dct[len(word)].append(word)

# Result
defaultdict(<class 'list'>, {3: ['The', 'the', 'the'], 6: ['silver', 'number'], 8: ['proposes', 'blushing', 'explores'], 5: ['burst'], 4: ['fast', 'iron'], 10: ['impossible']})
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用简单的列表推导random.choice来选择与第一个列表中每个元素的长度匹配的随机单词.如果字长不是在你的字典中,填充-1:

final = [random.choice(dct.get(len(w), [-1])) for w in l1]

# Output
['The', 'silver', 'blushing']
Run Code Online (Sandbox Code Playgroud)

根据明确的要求进行编辑
这是一种方法,如果列表2中不存在重复,则满足不允许重复的要求:

for word in l2:
    dct[len(word)].append(word)

for k in dct:
    random.shuffle(dct[k])

final = [dct[len(w)].pop() for w in l1]
# ['The', 'silver', 'proposes']
Run Code Online (Sandbox Code Playgroud)

这种方法将IndexError在第二个列表中存在如果不够的话来完成分发.