如何从包含多个值的键中获取特定值?

时间:2015-11-29 14:59:29

标签: python python-2.7

我是python的新手。

与标题一样,我希望从多个值的键中获取特定值。

我正在尝试编写一个代码,该代码将第一列作为键,其余部分作为文本文件中的值。然后我想在字典中获得具有多个值的特定值。

文本文件示例:

  

111 Josh 12 17 20 21

     

112 Alice 13 18 25 24

     

113 Rick 15 17 30 21

这几乎就是我的代码:

Q=raw_input("Your ID") 
def f():
  d1={}
  with open('file.txt') as r:
    for line in r:
      (a,b,c,d,e,f)=line.split()
      if a==Q:
        d1[a]=b,c,d,e,f
  return d1


def f2():
  x=f()
  name=x[a,b]
  age=x[a,c]
  score1=x[a,d]
  score2=x[a,e]
  score3=x[a,f]
  print str(name)+ str(age) +str(score1)+ str(score2) +str(score3)

f2()

我的期望是:

  

112

     

Alice 13 18 25 24

p.s:by“x [a,b]”我的意思是,从d1开始,取a个键,b值。

p.s2:我知道x [a,b]错了。我只想表明我的意图。

1 个答案:

答案 0 :(得分:1)

我认为这可能是你想要做的。我使它工作并稍微改进了一点,但它仍然保留了改进的空间(更好的命名,传递文件名等)。

import collections

# namedtuple is a regular tuple that can be accessed by name rather than just by position
NameRecord = collections.namedtuple("NameRecord", "id name age score1 score2 score3")

# Return the first record in file where the first element of the line
# matches the given id
def f(id):
  with open('file.txt') as r:
    for line in r:
        # Split the line and pass as arguments to a new NameRecord
        record = NameRecord(*line.split())
        if record.id == id:
            return record
  return None

def f2():
    id = raw_input("Your ID") 
    record = f(id)
    if record:
        #print '{} {} {} {} {}'.format(*record[1:])
        print '{} {} {} {} {}'.format(record.name,
                                      record.age,
                                      record.score1,
                                      record.score2,
                                      record.score3)
    else:
        print 'Id not found:', id

f2()

另一种使用发电机的解决方案与第一个解决方案不同,这个将打印所有匹配id的记录。如果您只想要第一个,请在print语句后面的循环中放置一个return语句。

NameRecord = collections.namedtuple("NameRecord", "id name age score1 score2 score3")

# generator from using yield
def lines_from_file(filename):
    with open(filename) as f:
        for line in f:
            yield line

# generator from generator expression
def name_records_from_lines(lines):
    return (NameRecord(*line.split()) for line in lines)

def name_records_matching_id(records, id):
    for record in records:
        if record.id == id:
            yield record

# identical to the method above for learning purposes
def name_records_matching_id_2(records, id):
    return (record for record in records if record.id == id)

id = raw_input("Your ID") 
lines = lines_from_file('file.txt')
records = name_records_from_lines(lines)
matching_records = name_records_matching_id(records, id)
# Note: if your code is simple enough, you don't need to define a method:
# matching_records = (record for record in records if record.id == id)
for record in matching_records:
    print record.name, record.age, record.score1, record.score2, record.score3