简体   繁体   English

在每个子列表中打印带有字符串和整数的格式化嵌套列表

[英]Printing formatted nested lists with strings and integers in each sublist

list = [["John Doe", 40], ["Jane Doe", 38],["Joe Bloggs", 34]]

I've got a nested list similar to the above, with each sublist containing a string and an integer. 我有一个类似于上面的嵌套列表,每个子列表包含一个字符串和一个整数。 When hitting print within my for loop I get the ugly, unformatted output; 在for循环中点击print时,我得到的是丑陋的,未格式化的输出;

for item in list:
print(item)

I'd like to tidy it up a bit (ie remove brackets and quotations) but can't get my head around how I'd do it. 我想整理一下(例如,删除括号和引号),但无法理解如何做。 Can someone help me out? 有人可以帮我吗?

Try the * , sometimes called the "splat" operator, which unpacks the list for you. 尝试* ,有时也称为“ splat”运算符,它将为您解压缩列表。

items = [["John Doe", 40], ["Jane Doe", 38],["Joe Bloggs", 34]]

for item in items:
    print(*item)

# OUTPUT
# John Doe 40
# Jane Doe 38
# Joe Bloggs 34

You are working with a multidimensional list. 您正在使用多维列表。

This code works for a one dimension list: 此代码适用于一维列表:

for item in list:
    print(item)

You can retrieve any element in a list using a number, using the position in the list of the element. 您可以使用数字,使用元素列表中的位置来检索列表中的任何元素。 The number 0 is for first element, The number 1 for second element in the list and so on. 数字0表示列表中的第一个元素,数字1表示列表中的第二个元素,依此类推。

So with: 因此:

list = [["John Doe", 40], ["Jane Doe", 38],["Joe Bloggs", 34]]
list[0]

You retrieve the first list inside the original list: 您检索原始列表内的第一个列表:

["John Doe", 40]

So with the code: 因此,使用代码:

list = [["John Doe", 40], ["Jane Doe", 38],["Joe Bloggs", 34]]
list[0][0]

You retrieve the name inside the first embeded list: 您在第一个嵌入列表中检索名称:

"John Doe"

And with the code: 并加上代码:

list = [["John Doe", 40], ["Jane Doe", 38],["Joe Bloggs", 34]]
list[0][1]

You retrieve the age in the embeded list: 您在嵌入列表中检索年龄:

"40"

You can make a iteration in a multidimensional list refering each element by its position in the list: 您可以在多维列表中进行迭代,通过每个元素在列表中的位置来引用它:

list = [["John Doe", 40], ["Jane Doe", 38],["Joe Bloggs", 34]]

for elemento in list:
    print("Name: " + str(elemento[0]))
    print("Age: " + str(elemento[1]))
    print(" - - -  - - -  - - -  - - -  - - -  - - -  - - - ")

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

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