【问题标题】:Jumping to a specific line in python file operations跳转到 python 文件操作中的特定行
【发布时间】:2015-12-22 17:54:29
【问题描述】:

我有一个清单,

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"]

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

【问题讨论】:

  • 你在用所有的嵌套循环做什么?
  • 试图接触主要品牌..看起来很糟糕..我知道
  • 我不太了解客户的高度偏好,您能解释一下您期望的输出以及原因吗?
  • mercedes: a,b,c.. vs 被列为客户偏好.. 同样“a”是最受欢迎的元素,c 是最少的.. 根据给定的知识 i必须从最受欢迎和最不受欢迎的变量中排序
  • 变量与问题有什么关系?

标签: python file loops for-loop


【解决方案1】:

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

这样试试

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 文件中的汽车名称不匹配,您的字典调用将失败。

【讨论】:

    【解决方案2】:

    不确定要对不在行中的任何字母做什么,但您可以使用 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 中的键将在列表末尾排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 2018-02-06
      • 1970-01-01
      • 2015-04-07
      • 2019-05-08
      • 1970-01-01
      • 2023-01-25
      相关资源
      最近更新 更多