python - 基于元组列表创建新列表
问题描述
假设有一个元组列表:
for something in x.something()
print(something)
它返回
('a', 'b')
('c', 'd')
('e', 'f')
('g', 'h')
('i', 'j')
我还创建了另外两个列表,其中包含来自 x.something() 的某些元素:
y = [('a', 'b'), ('c', 'd')]
z = [('e', 'f'), ('g', 'h')]
所以我想将 x.something() 中的元组分配给基于 y 和 z 的新列表
newlist = []
for something in x.something():
if something in 'y':
newlist.append('color1')
elif something in 'z':
newlist.append('color2')
else:
newlist.append('color3')
我想要的是新列表看起来像:
['color1', 'color1', 'color2', 'color2', 'color3']
但我有
TypeError: 'in <string>' requires string as left operand, not tuple
出了什么问题以及如何解决?
解决方案
我认为你想得到if something in y
而不是if something in 'y'
因为它们是两个单独的列表,而不是字符串:
newlist = []
for something in x.something():
if something in y:
newlist.append('color1')
elif something in z:
newlist.append('color2')
else:
newlist.append('color3')
推荐阅读
- javascript - How do you pass HTML variables to google app scripts
- javascript - 为什么我们需要在这个例子中使用 THIS 关键字?
- reactjs - 如何在卸载 React 模式登录组件之前更新本地存储值
- python - 在python的setter中调用方法
- laravel - 在 Eloquent 中使用 orWhere()
- reactjs - 使用 Thunk 将数据从 Redux 存储加载到 React 状态
- ios - IOS应用程序即使根本不工作也能做事吗(Killed/Non-running state)
- android - 在实时布局检查器中手动选择活动(Android Studio 4.0)
- c++ - 命名空间 std:: 不包含可选
- node.js - firebase,我如何根据用户 ID 获得特定结构