简体   繁体   English

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

[英]How to print all words of a for loop in one line

I have following set of data. 我有以下数据集。

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

I want my output to look like: 我希望我的输出看起来像:

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

Right now my output looks like this with the following code. 现在,我的输出如下所示。

Output: 输出:

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

Code: 码:

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

Try this (it only prints for john, maria and 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))

Output: 输出:

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

You should first collect the data for each person, and then you can print for each person, one at a time like: 您应该首先收集每个人的数据,然后可以为每个人一次打印,例如:

Code: 码:

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)

Results: 结果:

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

You can use python's defaultdict for this: 您可以为此使用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)

Here's a different approach in which you collect the names of all person from your input list, then you collect and combine all information associated with each person and finally you print these information: 这是一种不同的方法,您可以从输入列表中收集所有人的姓名,然后收集并合并与每个人相关的所有信息,最后打印这些信息:

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))

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM