我需要帮助解决一个难题。
假设我们已经使用read方法将文件加载到字符串粘度数据中。粘度数据包含以下数据(按气体、C、T_0、mu_0的顺序排列):

viscosity_data = '''air,120,291.15,18.27
nitrogen,111,300.55,17.81
oxygen,127,292.25,20.18
carbon dioxide,240,293.15,14.8
carbon monoxide,118,288.15,17.2
hydrogen,72,293.85,8.76
ammonia,370,293.15,9.82
sulphur dioxide,416,293.65,12.54'''

将字符串粘度数据中的数据转换为嵌套字典mu_数据,以便我们可以查找C、T0和μ0,查找名称为mu_数据[name][X]的气体,其中X可以是“C”、“T_0”或“mu_0”之一。mu_数据中的数值都应该是浮点数。
例如,以下语句应为真:
mu_data['air']['C'] == 120.0
mu_data['hydrogen']['T_0'] == 293.85
mu_data['sulphur dioxide']['mu_0'] ==12.54

到目前为止,我还不确定从这里走到哪里:
mu_data = {}
#mu_data master
for data in viscosity_data:
    mu_data[name] = viscosity_data

最佳答案

你可以通过听写理解来做到这一点:

viscosity_data = '''air,120,291.15,18.27
nitrogen,111,300.55,17.81
oxygen,127,292.25,20.18
carbon dioxide,240,293.15,14.8
carbon monoxide,118,288.15,17.2
hydrogen,72,293.85,8.76
ammonia,370,293.15,9.82
sulphur dioxide,416,293.65,12.54'''

viscosity_data = [air_data.split(",") for air_data in viscosity_data.split("\n")]
mu_data = {air_name:{"c": c, "T_0": T_0, "mu_0": mu_0} for air_name,c,T_0,mu_0 in viscosity_data}

或者只在一行中使用map
mu_data = {air_name:{"c": c, "T_0": T_0, "mu_0": mu_0} for air_name,c,T_0,mu_0
           in map(lambda x: x.split(","), viscosity_data.split("\n"))}

输出
{'air': {'T_0': '291.15', 'c': '120', 'mu_0': '18.27'},
 'ammonia': {'T_0': '293.15', 'c': '370', 'mu_0': '9.82'},
 'carbon dioxide': {'T_0': '293.15', 'c': '240', 'mu_0': '14.8'},
 'carbon monoxide': {'T_0': '288.15', 'c': '118', 'mu_0': '17.2'},
 'hydrogen': {'T_0': '293.85', 'c': '72', 'mu_0': '8.76'},
 'nitrogen': {'T_0': '300.55', 'c': '111', 'mu_0': '17.81'},
 'oxygen': {'T_0': '292.25', 'c': '127', 'mu_0': '20.18'},
 'sulphur dioxide': {'T_0': '293.65', 'c': '416', 'mu_0': '12.54'}}

关于python - 从文件制作嵌套字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46750086/

10-12 18:14