美文网首页
python学习----字典

python学习----字典

作者: 橘颂betty | 来源:发表于2017-11-10 07:13 被阅读0次

代码如下

# __author__ == 'xjiao'
# -*- coding:utf-8 -*-

import csv

def readTable(fileobj):
    """Read Periodic Table file into a dict.with element symbol as key."""
    dataFile = csv.reader(fileobj)
    periodicTable = {}

    for row in dataFile:
        #ignore header rows:elements begin with a number
        if row[0].isdigit():
            symbol = row[1]
            periodicTable[symbol] = row[:8]   #ignore end of row

    return periodicTable

def parseElement(elementStr):
    """Parse element string into symbol and quantity.
    e.e. Si2 return ('Si',s)"""

    symbol = ""
    quantity = ""
    for ch in elementStr:
        if ch.isalpha():
            symbol = symbol + ch
        else:
            quantity = quantity + ch
    if quantity == "":#if no number,default is 1
        quantity = 1

    return symbol,int(quantity)

#Read file
fileHandle = open('Periodic-Table.csv','rU')

#Create Dictionary of Periodic Table using element symbols as keys
periodicTable = readTable(fileHandle)

#Promot for input and convert compound into a list of element
compoundString = \
    raw_input("Input a chemical compound,hyphenated,e.g. C-O2:")
compoundList = compoundString.split('-')

#Initialize atomic mass
mass = 0
print "The compound is composed of:",

#Parse comound list into symbol-quantity pairs,print name,and add mass
for c in compoundList:
    symbol,quantity = parseElement(c)
    print periodicTable[symbol][5], #print element name
    mass = mass +quantity*float(periodicTable[symbol][6])

print "\n\nThe atomic mass of the compound is",mass

fileHandle.close()

输出结果如下:

D:\python\python.exe E:/python_project/Chapter8-3.py
Input a chemical compound,hyphenated,e.g. C-O2:H2-S-O4
The compound is composed of: hydrogen sulfur oxygen 

The atomic mass of the compound is 98.086

Process finished with exit code 0

相关文章

  • Day01自学 - Python 字典(Dictionary)

    学习参考博客地址:Python 字典(Dictionary) | Python 优雅的操作字典 一、创建字典 字典...

  • Python学习3

    python 学习三 字典

  • 2018-06-29

    python学习 学习python字符串、列表、元组、字典、日期和时间模块

  • 读书笔记 | Python学习之旅 Day4

    Python学习之旅 读书笔记系列 Day 4 《Python编程从入门到实践》 第6章 字典 知识点 字典:相互...

  • Python学习-字典(dict)

    查看所有Python相关学习笔记 字典(dict) 字典内元素是无序的 新增(创建)字典(key-value) k...

  • Python学习——字典

    Python学习——字典 字典的外在样式如: { },字典内可包含各种数据,例如列表、字典,且其中以键值对的形式展...

  • Python 字典学习

  • python学习----字典

    代码如下 输出结果如下:

  • Python 字典学习

    创建字典的两种方法: dict dict 访问字典中元素的两种方法: '山山' '山山' 判断字典是否存在某一元素...

  • 2018-10-30

    Python字典学习 在Python中,列表和字典常用于存储数据。 日常生活中,经常会去买饮料。饮料有果汁、咖啡、...

网友评论

      本文标题:python学习----字典

      本文链接:https://www.haomeiwen.com/subject/unpvmxtx.html