在嵌套字典中显示键/值对中的文本

2024-04-20 07:53:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个新手。 我试着把元素周期表中的元素打印到屏幕上,就像周期表本身一样。我用('-')来分隔我还没有写在字典里的符号。我只使用两个词条的嵌套字典来减少混淆。你知道吗

Training Source最后一个练习。你知道吗

我在别处问过这个问题,有人(正确地)建议使用str.join公司(列表)但这不是教程的一部分。 我试着自学,我想理解。没有学校,没有工作,没有老师。你知道吗

链接教程底部的提示是:

1.“使用for循环遍历每个元素。选择元素的行号和列号。”

2.“使用两个嵌套for循环打印元素的符号或一系列空格,具体取决于该行的填充程度。”

我想这样解决。提前谢谢。 注*不,请输入中级、中级或高级代码,本教程只介绍与变量、字符串、数字、列表、元组、函数(初学者)、if语句、while循环、基本终端应用程序和字典相关的代码。你知道吗

最后,我想让这个表本身印上真正周期表的形状。如果你能为新手输入一点代码,那会很有帮助的,谢谢。你知道吗

我的尝试(错误):

ptable = {'mercury':{'symbol':'hg','atomic number': '80','row': '6','column': '12','weight':'200.59',}, 'tungsten':{'symbol':'w','atomic number':'74','row':'6','column':'6','weight':'183.84'},}

for line in range(1,7): 
    for key in ptable:
        row = int(ptable[key]['row'])
        column = int(ptable[key]['column'])
        if line != row:
                print('-'*18)
        else:
                space = 18 - column
                print('-'*(column-1)+ptable[key]['symbol']+'-'*space)

输出:

------------------
------------------
------------------
------------------
------------------
------------------
------------------
------------------
------------------
------------------
-----------hg------
-----w------------

输出应该有7行元素周期表。它应该在元素周期表的正确位置显示每个元素的符号。因为库中只有两个元素,所以应该在正确的位置显示Hg和W

经验丰富的程序员解决方案:

for line in range(1, 8): # line will count from 1 to 7

# display represents the line of elements we will print later

# hyphens show that the space is empty

# so we fill the list with hyphens at first

display = ['-'] * 18

for key in ptable:
    if int(ptable[key]['row']) == line:
        # if our element is on this line
        # add that element to our list
        display[int(ptable[key]['column']) - 1] = ptable[key]['symbol']

# str.join(list) will "join" the elements of your list into a new string
# the string you call it on will go in between all of your elements
print(''.join(display)) 

Tags: thekeyin元素foriflinecolumn
1条回答
网友
1楼 · 发布于 2024-04-20 07:53:55

老实说,我认为这个代码并不难理解,我认为试图改变它只会使它更复杂。我将在最后为您提供一些链接,让您检查并了解您似乎也不了解的“”join()方法和range()函数。你说你想自己学Python,那是件好事!(我也在做)但这并不意味着你必须坚持一个教程;)。你可以超越它,也可以跳过你不在乎的部分,等你需要的时候再来。如果你需要关于方法的解释(比如''join)或者其他任何东西,请告诉我。抱歉,如果这对你没有帮助;(。你知道吗

链接:

The .join() method

The range() function

相关问题 更多 >