首页 文章

我在for循环中有两个列表,我想格式化输出

提问于
浏览
0

我正在尝试为亲戚的种类和姓名获取用户输入 .

for relatives in victim['other_relatives_kind'], victim['other_relatives_name']:
    print(relatives)

如果用户输入 ['other_relatives_kind'] 中的Brother和Aunt以及 ['other_relatives_name'] 中的Andreas Petersen和Anni Nielsen,我会得到以下输出:

['Brother', 'Aunt']

['Andreas Petersen', 'Anni Nielsen']

如何使输出如下:

兄弟:Andreas Petersen阿姨:Anni Nielsen

可能存在“无限”数量的输入亲属 .

1 回答

  • 3

    您可以使用str.join使用任何arbirary分隔符加入 str 的列表 .

    您可以使用zip将两个列表合并为一个列表,其中每个元素都是两个项目的元组 .

    以下是使用 zipstr.join() 的示例:

    victim = {
        'other_relatives_kind': ['Brother', 'Aunt'],
        'other_relatives_name': ['Andreas Petersen', 'Anni Nielsen']
    }
    
    zipped_data = zip(
        victim['other_relatives_kind'],
        victim['other_relatives_name'])
    print ('\n'.join('{kind}: {name}'.format(kind=kind, name=name)
                     for kind, name in zipped_data))
    

    结果:

    Brother: Andreas Petersen
    Aunt: Anni Nielsen
    

    请注意,使用f-strings可以在Python3.6中简化 print 调用:

    print ('\n'.join(f'{kind}: {name}' for kind, name in zipped_data))
    

相关问题