【问题标题】:Reversing some words randomly in a list of lists [duplicate]在列表列表中随机反转一些单词[重复]
【发布时间】:2022-01-16 14:54:43
【问题描述】:

所以我有一个列表列表,其中每个元素对应于特定文档的单词,例如格式是:

[['alice','wonderland',......],['cat','hat',....],......]

我有一个包含在此列表列表中的单词的小列表,我想以 50% 的机会在该列表列表中反转这些单词(例如,如果 'alice' 在我的列表中,大约 50%列表列表中出现的“alice”将变为“ecila”。

到目前为止,这是我的代码:

words = ['alice','wonderland','cat','hat',....]
sublist = ['alice','cat','hat']

import random
output = [w[::-1] if w in sublist and random.choice([True, False]) else w
       for w in words]

我似乎只能在 words 是一个列表时让它工作,但在它是一个列表列表时不能工作,有人可以帮忙吗?

【问题讨论】:

  • 在执行列表列表或dicts的dict时,您必须执行嵌套for循环

标签: python string list random


【解决方案1】:

正如 cmets 中提到的,您应该使用嵌套循环。这里有一个 带有嵌套循环的代码来实现你所追求的:

words = [['alice','wonderland'],['cat','hat']]

sublist = ['alice','cat','hat']

import random
output = [[w[::-1] if w in sublist and random.choice([True, False])  else w
      for w in wordsList ]for wordsList in words]
output

这是用于测试它的 colab: https://colab.research.google.com/drive/1uEyM8CPDg_eMhpQl9385CGabnAL2OLn-?usp=sharing

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2020-02-14
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2016-04-24
    • 2019-07-05
    相关资源
    最近更新 更多