简体   繁体   English

在Python中使用for循环和嵌套循环

[英]Using for loops with nested loops in python

I need to print each element with its atomic number and weight each on a separate line, with a colon between the name and atomic number and weight, however, it prints each three times, I understand why but have no idea how to remedy it. 我需要在单独的一行上打印每个元素的原子序号和权重,并在名称和原子序数和重量之间加上一个冒号,但是每个元素都要打印三遍,我知道为什么但不知道如何解决。 Help 救命

Here is the code I used: 这是我使用的代码:

elements = [['beryllium', 4, 9.012], ['magnesium', 12, 24.305], ['calcium', 20, 40.078], ['strontium', 38, 87.620], ['barium', 56, 137.327], ['radium', 88, 266.000]]

for x in elements:
    for i in x:
        print str(x[0]), ':', str(x[1]), str(x[2])

You are looping over the 3 nested elements; 您正在遍历3个嵌套元素; simply remove the nested for : 简单地删除嵌套for

for x in elements:
    print str(x[0]), ':', str(x[1]), str(x[2])

You can also have Python unpack the elements into separate names; 您还可以让Python将元素解压缩为单独的名称; note that the explicit str() calls are not needed here as you are not concatenating the values; 注意,这里不需要显式的str()调用,因为您没有串联值。 let print take care of converting the values to strings for you: print负责为您将值转换为字符串:

for name, number, weight in elements:
    print name, ':', number, weight

Next, use string formatting to get more control over the output: 接下来,使用字符串格式来更好地控制输出:

for name, number, weight in elements:
    print '{:>10}: {:3d} {:7.3f}'.format(name, number, weight)

and you get nicely formatted output: 您将获得格式正确的输出:

>>> for name, number, weight in elements:
...     print '{:>10}: {:3d} {:7.3f}'.format(name, number, weight)
... 
 beryllium:   4   9.012
 magnesium:  12  24.305
   calcium:  20  40.078
 strontium:  38  87.620
    barium:  56 137.327
    radium:  88 266.000

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

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