在列表列表中随机反转一些单词

Reversing some words randomly in a list of lists

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

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

我有一小部分单词包含在这个列表列表中,我想以 50% 的几率反转该列表列表中的这些单词(例如,如果 'alice' 在我的列表中, 'alice' 在列表列表中大约 50% 的出现将变成 '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 是一个列表时让它工作,但当它是列表列表时却不行,有人能帮忙吗?

正如评论中提到的,您应该使用嵌套循环。这里有一个 带有嵌套循环的代码来实现你想要的:

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