【发布时间】:2022-01-20 01:04:03
【问题描述】:
我有一长串列表words_lists,其中包含特定文档的单词标记(也包含重复项),还有一个包含words_list 中的一些单词的子列表。
我正在尝试在 words_list 中反转 EXACTLY HALF 子列表 RANDOMLY 中出现的单词(所以不仅仅是反转单词的前半部分等),请注意word_list 应该保持相同的顺序。
这是我目前所拥有的:
words_list = [['test', 'hello'] ,['world', 'what', 'favourite'],['test',...]..]
sublist = ['test','world']
import random
out = [w[::-1] if w in sublist and random.choice([True, False]) else w
for w in words_list]
它工作得相当好,但为了准确起见,我希望 EXACTLY 一半的事件被反转。
我创建了一些代码(见下文),它对包含大小为 occurrances 的 True 或 False 的列表进行洗牌,但我无法理解如何在原始列表中使用它理解循环,谁能帮忙
decisions = []
for i in range(occurrences):
if i < occurrences/2:
decisions.append(True)
else:
decisions.append(False)
random.shuffle(decisions)
【问题讨论】:
-
因为
words_list是一个列表列表,所以w是一个列表,而不是一个单词。if w in sublist如何找到匹配项?
标签: python arrays string list random