【问题标题】:Skip NA using random choice?使用随机选择跳过 NA?
【发布时间】:2022-08-04 00:10:45
【问题描述】:

语境

一个空列表:

my_list = []

我还有一个字符串列表:

words_list = [[\'this\', \'\', \'is\'], [\'a\', \'list\', \'\'], [\'of\', \'lists\']]

但请注意,列表中有一些元素为空。

理想输出

我想从words_list 中的每个列表中随机选择一个非空元素,并将其作为元素附加到my_list

例如

>> my_list 
[\'this\', \'list\', \'of\']

我目前拥有的

for i in words_list:
    my_list.append(random.choice(words))

我的问题

但它抛出了这个错误:

  File \"random_word_match.py\", line 56, in <module>
    get_random_word(lines)
  File \"random_word_match.py\", line 51, in get_random_word
    word_list.append(random.choice(words))
  File \"/Users/nathancahn/miniconda3/envs/linguafranca/lib/python3.7/random.py\", line 261, in choice
    raise IndexError(\'Cannot choose from an empty sequence\') from None
IndexError: Cannot choose from an empty sequence

我不想要的

我不想只附加第一个非空元素 我不希望 my_list 中的空值

  • 也许您应该设置一个种子来重现您的错误,因为它对我有用,因为 \'\' 不被解释为无。为什么不首先选择之前删除空元素?即使使用实际的Nones [np.random.choice(x) for x in l],这一个班轮也对我有用

标签: python list random nan


【解决方案1】:

试试下面的代码,看看它是否适合你:

import random
my_list = []
words_list = [['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']]
for sublist in words_list:
    filtered_list = list(filter(None, sublist))
    my_list.append(random.choice(filtered_list))
print(my_list)

【讨论】:

  • 列表中没有None,所以这个过滤器实际上并没有帮助。此外,这可以重写为单行列表理解。
  • 有趣的是,它对我有用。
【解决方案2】:

也许你可以尝试这样开始思考:

>>> for word in words_list:
    wd = choice([w for w in word if w])   # if w is non-null, choice will pick it...
    print(wd)

# then just add those non-null word into your my_list --- leave as exercise.
# Like this: 
>>> for word in words_list:
    wd = choice([w for w in word if w])
    my_list.append(wd)    
  
>>> my_list
['this', 'a', 'lists']

# Later, you could even simplify this into a List Comprehension. 

【讨论】:

    猜你喜欢
    • 2021-04-05
    • 2011-01-28
    • 2021-10-18
    • 2013-02-10
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多