从嵌套列表中获取一组唯一值

Jas*_*e N 0 python set

我有这个嵌套列表 X_train

X_train = [['sunny', 'hot', 'high', 'FALSE'],
 ['sunny', 'hot', 'high', 'TRUE'],
 ['overcast', 'hot', 'high', 'FALSE'],
 ['rainy', 'mild', 'high', 'FALSE'],
 ['rainy', 'cool', 'normal', 'FALSE'],
 ['rainy', 'cool', 'normal', 'TRUE'],
 ['overcast', 'cool', 'normal', 'TRUE'],
 ['sunny', 'mild', 'high', 'FALSE'],
 ['sunny', 'cool', 'normal', 'FALSE'],
 ['rainy', 'mild', 'normal', 'FALSE'],
 ['sunny', 'mild', 'normal', 'TRUE'],
 ['overcast', 'mild', 'high', 'TRUE'],
 ['overcast', 'hot', 'normal', 'FALSE'],
 ['rainy', 'mild', 'high', 'TRUE']]
Run Code Online (Sandbox Code Playgroud)

我想生成一个列表,其中的第 n 行X_train包含X_train. 所以预期的输出应该是:

[{'overcast', 'rainy', 'sunny'},
 {'cool', 'hot', 'mild'},
 {'high', 'normal'},
 {'FALSE', 'TRUE'}]
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

questions=[]
f=set({w for row in X_train for w in row})
questions+=[f]
Run Code Online (Sandbox Code Playgroud)

其输出就像所有唯一值的集合,这不是我预期的输出。我应该如何纠正以按预期修复我的输出(建议我使用 set 但我不确定如何以正确的方式修复它)

[{'FALSE',
  'TRUE',
  'cool',
  'high',
  'hot',
  'mild',
  'normal',
  'overcast',
  'rainy',
  'sunny'}]
Run Code Online (Sandbox Code Playgroud)

有什么想法可以帮助我吗?提前致谢

Mar*_*yer 6

您可以zip()从列表中获取列。拆开列*是这里的诀窍。然后只需取一组列:

X_train = [['sunny', 'hot', 'high', 'FALSE'],
 ['sunny', 'hot', 'high', 'TRUE'],
 ['overcast', 'hot', 'high', 'FALSE'],
 ['rainy', 'mild', 'high', 'FALSE'],
 ['rainy', 'cool', 'normal', 'FALSE'],
 ['rainy', 'cool', 'normal', 'TRUE'],
 ['overcast', 'cool', 'normal', 'TRUE'],
 ['sunny', 'mild', 'high', 'FALSE'],
 ['sunny', 'cool', 'normal', 'FALSE'],
 ['rainy', 'mild', 'normal', 'FALSE'],
 ['sunny', 'mild', 'normal', 'TRUE'],
 ['overcast', 'mild', 'high', 'TRUE'],
 ['overcast', 'hot', 'normal', 'FALSE'],
 ['rainy', 'mild', 'high', 'TRUE']]

values = [set(col) for col in zip(*X_train)]
Run Code Online (Sandbox Code Playgroud)

给你价值:

[{'overcast', 'rainy', 'sunny'},
 {'cool', 'hot', 'mild'},
 {'high', 'normal'},
 {'FALSE', 'TRUE'}]
Run Code Online (Sandbox Code Playgroud)