【问题标题】:Reversing half the words in a list of lists randomly in Python在Python中随机反转列表列表中的一半单词
【发布时间】: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


【解决方案1】:

列出word_list 中所有在sublist 中的单词的索引。使用random.sample() 随机选择这些索引的一半。然后用这些索引反转原始列表的元素。

indexes = [i for i, w in enumerate(words_list) if w in sublist]
random_half = set(random.sample(indexes, len(indexes)//2))
out = [w[::-1] if i in random_half else w for i, w in enumerate(words_list)]

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2013-12-17
    • 2018-04-11
    • 2021-11-02
    • 2017-03-12
    相关资源
    最近更新 更多