如何使它只在dict- python中显示键

时间:2014-04-14 07:46:51

标签: python list dictionary

因此用户输入他们想要阅读的txt文件,文本文件通常包含

a eats b
b eats c
c eats d

f_web = open(input('enter text wanted evaluated:'))

def web(enter text):
    food_web = f_web
    tuple_data = []
    for line in food_web:
        a = line.strip().split()
        tuple_data.append((a[0].strip(), a[-1].strip()))
    output = defaultdict(list)
    for x, y in tuple_data:
            output[x].append(y)
    print ('Predators and Prey:')
    for Predators, Prey in output.items():
        values = ' , '.join(Prey)
        print ('\t{} eats {}'.format(Predators, values))
     return web
    web(f_web)

我希望我的程序显示当前的东西,然后显示哪些捕食者只是捕食者而且从不被吃掉。所以喜欢这个

从未吃过:

2 个答案:

答案 0 :(得分:1)

您应该尝试使用dictionary

fl = str(input('Enter text wanted evaluated: '))

with open(fl, 'r') as f:
f = f.read().split('\n')

f_dict = {}

for i in f:
    i = i.split()
    if i[0] in f_dict:
        f_dict[i[0]].append(i[2])
    else:
        f_dict[i[0]] = [i[2]]

a = []
for i in f_dict:
    for j in f_dict.values():
        if i in j:
            break
        a.append(i)

a = list(set(a))

for i in f_dict:
    print i+' eats '+', '.join(f_dict[i])

print('')
print('Never Eaten')
for i in a:
    print i

[Out]:
a eats b, d, c
c eats d
b eats c, d

Never Eaten
a

答案 1 :(得分:0)

步骤:

  1. 打开文件并阅读每一行,按'eats'分割。
  2. 将第一个值附加到名为predator的列表中,如果它尚未位于prey中(如果它不是2 nd 值),如果它在predator中并且它是猎物,请将其从predator移除,并将其从prey移除。
  3. 打印predator中的所有值。

    open('file.txt')
    predators = []
    eaten = []
    for lines in file:
        lines = lines.split('eats')
        predator, prey = lines
        if predator not in eaten:
            predators.append(predator)
        if prey in predator:
            del(predator[prey])
        eaten.append(prey)
    print 'Never eaten:'
    for k in predators:
        print k
    
  4. 运行方式:

    Never eaten:
    a