我在列表表单中有一个数据集,并希望在特定条件下将其转换为另一个数据集。
条件
"a" = 1
"b" = 2
"c" = 3
input_list = ["a", "b", "c"]
# something happens
output_list = [1, 2, 3]
该怎么办呢?
发布于 2022-02-20 12:47:41
conditions = {
"a": 1,
"b": 2,
"c": 3
}
input_list = ["a", "b", "c"]
output_list = [conditions[x] for x in input_list]
发布于 2022-07-03 12:21:57
你想要实现的是一个映射。
您的条件是映射、字典(Python )或哈希表。其中的每个值(如1
)对应于数据集中的一个键(如"a"
)。
要表示此映射,可以使用类似于表的数据结构将键映射到值。在Python中,这种数据结构称为字典:
mapping = {"a": 1, "b": 2, "c": 3} # used to translate from key to value (e.g. "a" to 1)
input_list = ["a", "b", "c"]
# something happens
output_list = []
for v in input_list:
mapped_value = mapping[v] # get the corresponding value, translate or map it
print(v + " -> " + mapped_value)
output_list.append(mapped_value)
print(output_list) # [1, 2, 3]
另请参阅
https://stackoverflow.com/questions/71198608
复制相似问题