访问列表列表中的元素

access elements in list of lists

我是文本挖掘新手,我正在使用 Python。我有一个列表列表,每个列表都包含同义词簇,簇中的每个单词都有一个列表,其中包含它出现的句子数量。 我的列表是这样的

syn_cluster = [[['Jack', [1]]], [['small', [1, 2]], ['modest', [1, 3]], ['little', [2]]], [['big', [1]], ['large', [2]]]]

我想为每个集群分配外观列表中的 minmax,所以我希望结果像这样

[[['Jack', [1]]], [['small', 'modest, 'little'], [1, 3]], [['big', large], [1, 2]]]

我不确定您是否使用了最好的数据结构来解决您的问题。但是,如果您使用列表的列表来执行此操作,您可以执行以下操作:

from itertools import chain

serialized = []
for syn_words in syn_cluster:
    words = [w[0] for w in syn_words]
    freqs = list(chain.from_iterable([f[1] for f in syn_words]))
    min_max = [min(freqs), max(freqs)]
    # or:  min_max = list({min(freqs), max(freqs)}) if you want [1] instead of [1, 1]
    serialized.append([words, min_max])

serialized
>>> [[['Jack'], [1, 1]],
    [['small', 'modest', 'little'], [1, 3]],
    [['big', 'large'], [1, 2]]]

我想提出另一个解决方案。

from functools import reduce

response = []
for sublist in syn_cluster:
  list_flatt = reduce(lambda x,y: x + y, sublist, [])
  list_words  = [word for word in list_flatt if type(word) == str]
  numbers = reduce(lambda x, y: x + y, [number_list for number_list in list_flatt if type(number_list) == list], [])
  list_min_max = [min(numbers), max(numbers)] if len(set(numbers)) > 1 else list(set(numbers))
  response.append([list_words, list_min_max])


print(response)

输出:

[[['Jack', [1]]], [['small', 'modest', 'little'], [1, 3]], [['big', 'large'], [1, 2]]]

说明

您可以使用 functools 中的 reduce 函数来扁平化 syn_cluster 列表中的每个子列表。

# list_flatt become for example something like ['small', [1, 2], 'modest', [1, 3], 'little', [2]] and so on for each row of syn_cluster.

list_flatt = reduce(lambda x, y: x + y, sublist, []) 

将子列表展开后,可以使用理解列表来获取字符串元素。

list_words  = [word for word in list_flatt if type(word) == str]

然后您可以使用相同的逻辑来获取数字列表。

[number_list for number_list in list_flatt if type(number_list) == list]

但是这个列表有以下方式:[[1,2] [1,3,2], [1]],因此我再次使用了 reduce

numbers = reduce(lambda x, y: x + y, [number_list for number_list in list_flatt if type(number_list) == list], [])

之后,我们使用 minmax 值创建列表,并验证 numbers 列表的长度。

list_min_max = [min(numbers), max(numbers)] if len(set(numbers)) > 1 else list(set(numbers))