使用python从CSV文件查询

我有三个CSV文件,一个包含所有文件的列表,一个包含类型M的列表,另一个包含类型B的列表。这意味着第一个列表包含另外两个文件,但未指定其类型。 我想在第一个列表中添加一行以使用python指定片段的类型,这意味着对于第一个列表中的每个片段,检查它是否在列表M中,并在其类型列中添加M,否则添加B。 我的想法是创建一个词典列表(以后可以使用预先编写的Python库将其转换为CSV),看起来像这样:

l = [{'piece','type'}] # list of dictionaries

for c in allpieces: # this is the list of all pieces:
    l[{'piece'}] = c['piece'] # adding the piece number to the list of dictionaries from the list of all pieces
    for m in mlist: # list of pieces of type m
      if c['piece'] == m['piece']: # check of piece is found in listm
        l[{'type'}] = 'm' # Add an m in its column
        else: l[{'type'}] = 'b' # otherwise add b

这段代码显然没有做任何事情,我需要帮助对其进行调试。

zhichaoc21614879 回答:使用python从CSV文件查询

字典将键映射到类似{"key": "value}的值,而列表中的元素通过提供索引来访问,因此对于列表中的第一个元素,您可以执行list[0]来获取它。现在,如果您想将具有值的新键添加到字典中,可以像这样d["key"] = value一样添加它们。如果要添加到列表中,请执行list.append(value)。因此,在您的情况下,您想做的是创建一个包含字典的列表(我认为是)?这样看起来像这样:

allpieces = ["Queen","Tower","Rook"]
mlist = ["Pawn","Queen","Rook"]
l = []

for c in allpieces:
    if c in mlist:
        l.append({"piece": c,"type": "m"})
    else:
        l.append({"piece": c,"type": "b"})

print(l)

哪个列表中包含我们的字典,如下所示:

[{'piece': 'Queen','type': 'm'},{'piece': 'Tower','type': 'b'},{'piece': 'Rook','type': 'm'}]

现在,如果您要访问此列表中的元素,则可以执行l[0]["piece"]来获取"Queen"

本文链接:https://www.f2er.com/3131523.html

大家都在问