如何在一行中打印for循环的所有单词

时间:2018-02-25 18:38:06

标签: python python-3.x formatting

我有以下数据集。

set = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45), 
       ('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]

我希望我的输出看起来像:

John: m(23) m(45)
Maria: f(17)
Stacy: f(19) f(21)

现在我的输出看起来像这样,代码如下。

输出:

John:   m (23) 
Maria:   f (17) 
John:   m (45) 
Stacy:   f (19) 
Stacy:   f (21)

代码:

for ind in set:
    i = ind[0]
    if i == "john":
        print("John:"," ", str(ind[1]), "({0}) ".format(str(ind[2])))
    elif  i == "maria":
        print("Maria:"," ", str(ind[1]), "({0}) ".format(str(ind[2])))
    elif i == "stacy":
        print("Stacy:", " ", str(ind[1]), "({0}) ".format(str(ind[2])))

4 个答案:

答案 0 :(得分:1)

试试这个(它只为john,maria和stacy打印)

data = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45),
        ('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]

permitted_names = ['john', 'maria', 'stacy']
output = {}
for name, gender, age in data:
    if name not in permitted_names:
        pass
    elif name not in output:
        output[name] = '{0}({1})'.format(gender, age)
    else:
        output[name] += ' {0}({1})'.format(gender, age)

for name, value in output.items():
    print("{0}: {1}".format(name, value))

输出:

john: m(23) m(45)
maria: f(17)
stacy: f(19) f(21)

答案 1 :(得分:0)

您应首先收集每个人的数据,然后您可以为每个人打印,一次一个,如:

代码:

data = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45),
       ('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]

# collect per person, except Mary.  We don't like Mary
as_dict = {}
for datum in data:
    as_dict.setdefault(datum[0], []).append(datum)

# print each person, except Mary.  We don't like Mary.
for name, items in as_dict.items():
    if name in set('john stacy maria'.split()):
        msg = '{}: '.format(name) + ' '.join('{} ({})'.format(i[1], i[2])
                                             for i in items)
        print(msg)

结果:

john: m (23) m (45)
mary: f (32)
stacy: f (19) f (21)
maria: f (17)

答案 2 :(得分:0)

您可以使用python' defaultdict

In [37]: from collections import defaultdict

In [38]: data = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45),
    ...:        ('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]

In [39]: d = defaultdict(list)
In [40]: for name, *rest in data:
    ...:     d[name].append(rest)

In [41]: for name, value in d.items():
    ...:     if name in ('john', 'maria', 'stacy'):
    ...:         strvalues = (' {}({})'.format(a, b) for a, b in value)
    ...:         print('{}: {}'.format(name, ''.join(strvalues)))
john:  m(23) m(45)
maria:  f(17)
stacy:  f(19) f(21)

答案 3 :(得分:0)

这是一种不同的方法,您可以从输入列表中收集所有人的姓名,然后收集并合并与每个人相关的所有信息,最后打印这些信息:

inSet = [('john', 'm', 23), ('maria', 'f', 17), ('john', 'm', 45), 
       ('stacy', 'f', 19), ('stacy', 'f', 21), ('mary', 'f', 32)]

# Get names of people
nameSet = sorted(set([info[0] for info in inSet]))

# Get all info associated with each of these people
displayInfo = [ " ".join(["".join([info[1], '(' + str(info[2]) + ')']) for info in inSet if name==info[0]]) for name in nameSet]

# Print these information, after capitalizing first letter of each name.
for info in zip(map(str.title,nameSet),displayInfo):
print(": ".join(info))

输出:

John: m(23) m(45)
Maria: f(17)
Mary: f(32)
Stacy: f(19) f(21)