跳转到python文件操作中的特定行

时间:2015-12-22 17:54:30

标签: python file loops for-loop

我有一个清单,

brands= [["mercedes"], ["bmw"], ["ferrari"]]

名为brands.txt

的文件
mercedes: a, b, c, g , x , y
bmw: d, e, g, a, b, g, x 
ferrari: x, y, z, a, b, c

并最终另一个列表

variables = ["b", "c", "a", "y", "x", "z"]

我要做的是在第一个列表中选择一个品牌,并根据文件查找其变量,该文件按客户的高度偏好排序,这是我到目前为止编写的代码

 with open("brands.txt") as f:
    for line in f:
        line=line.replace("\n","").split(",")[1:]
        print(line)
        for i in line:
           for a in brands:
               for j in a:
                   for k in j:
                       if k in i:
                           line=line.split(",")[1:]
                           print line

选择品牌mercedes时的预期输出将类似于

["a", "b", "c", "x", "y"]

根据高度偏好,但是 我的代码不起作用......你能帮我解决一下吗?

2 个答案:

答案 0 :(得分:0)

我不明白你想要选择(如你所说)变量,所以我使用字典来保存你的文本数据。

尝试这样

customers = {}
for line in f:
    line_key = line.split(" ")[0][:-1]
    line_values = map(lambda x: x.strip(), line.split(":")[1].split(","))
    customers[line_key] = line_values

然后拨打密钥

print customers["mercedes"]

哪个给你

['a', 'b', 'c', 'g', 'x', 'y']

我必须指出文本数据是否已损坏且与Python文件中的汽车名称不匹配,您的字典调用将失败。

答案 1 :(得分:0)

不确定你想要对不在该行中的任何字母做什么,但你可以使用dict将索引映射到字母并使用它作为排序的键:

with open("in.txt") as f:
    variables = ["b", "c", "a", "y", "x", "z"]

    key = dict(zip(variables, range(len(variables))))

    d = dict((k, list(map(str.strip, v.split(",")))) for line in f for k, v in (line.strip().split(":"),))

    for k, v in d.items():
        v.sort(key=lambda x: key.get(x, float("inf")))
        print("Key = {}\nSorted values = {}\n".format(k,v))

输出:

Key = bmw
Sorted values = ['b', 'a', 'x', 'd', 'e', 'g', 'g']

Key = ferrari
Sorted values = ['b', 'c', 'a', 'y', 'x', 'z']

Key = mercedes
Sorted values = ['b', 'c', 'a', 'y', 'x', 'g']

你的dict中的所有值都将按排序顺序排列,使用float("inf"),因为默认值意味着不在dict中的键将在列表的末尾排序。