繁体   English   中英

我在python中遇到此代码的麻烦

[英]Im having trouble with this code in python

我有以下代码:

def create_dict(my_file):
    my_lines = my_file.readlines()   
    my_dict = {}

    for line in my_lines:
         items = line.split()
         key, values = items[0], items[2:3] + items[1:2] + items[5:6] +items[3:4] + items[4:5]
         my_dict[key] = values

    return my_dict

我需要它回来

{
  'asmith': ['Smith', 'Alice', 'alice.smith@utsc.utoronto.ca', 31, 'F'], 
  'rford': ['Ford', 'Rob', 'robford@crackshack.com', 44, 'M'] 
 }

但它的返回:

{
   'asmith': ['Smith', 'Alice', 'alice.smith@utsc.utoronto.ca', '31', 'F'], 

    'rford': ['Ford', 'Rob', 'robford@crackshack.com', '44', 'M']. 
 }

我需要将年龄值更改为整数,并且我尝试使用int(items[3:4]) ,但是它说对象必须是要转换为整数的字符串。 谁能找到原因呢?

尝试这个

int("".join(items[3:4]))  

尝试int(''.join(item)) 让我知道它是否有效。

应该为int(my_dict['asmith'][3])

items[3:4]返回一个不能转换为整数的列表。 items[3]似乎是年龄的位置。

说您的my_file有两行,如下所示:

asmith Smith Alice alice.smith@utsc.utoronto.ca  31 F       
rford Ford Rob robford@crackshack.com  44 M

您可以使用以下代码:

def create_dict(my_file):
    my_dict = {}
    with open(my_file, 'r') as f:  # close file without do it by yourself
        for line in f:  # it works even though the file has large size
            items = line.split()
            items[4] = int(items[4])  # convert age type from str to int
            my_dict[items[0]] = items[1:]
    return my_dict

测试:

>>> create_dict('/home/mingxian/Desktop/pythontest/testfile')
{'rford': ['Ford', 'Rob', 'robford@crackshack.com', 44, 'M'], 'asmith': ['Smith', 'Alice', 'alice.smith@utsc.utoronto.ca', 31, 'F']}

暂无
暂无

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

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