【问题标题】:Convert some objects in a list into int将列表中的一些对象转换为 int
【发布时间】:2019-09-23 11:22:33
【问题描述】:

所以我正在读取一个 csv 文件,使用 csv 文件中的输入访问 API,然后使用 Python 将响应打印到另一个文件中。

现在,我的 csv 文件包含 12 个请求参数,我希望其中 9 个作为整数传递,3 个作为字符串传递,同时访问 API。

我无法将它们转换为整数。 我的代码到现在如下(暂时跳过了 API 部分):

filepath = '/Users/AKG/Work/September19/U-model/Search.csv' 
import requests 
import json
import csv
import os
url = "http://internal-dsp-listing-lg-x.com/v1/predict/RSLD/v1" 
fp = open(filepath, encoding='utf-8') 
for cnt, line in enumerate(fp):
    line = line.split(',')
    d = {"customer_id": line[0],"listing_slot": line[1],"closingIn": line[2],"new_user": line[3],"last_mile_distance": line[4],"stress": line[5],"customer_user_agent": line[6],"listing_restaurant_sla": line[7],"request_id": line[8],"ld": line[9],"city_id": line[10],"restaurant_id": line[11].replace("\n","")} 
    print (line)

我的输出是:

['\ufeff87068', '4', '-1', '0', '0.916999995708465', '0.9608271718025208', 'ANDROID', '33', 'aa27f680-2ddb-4d61-b685-e29a15f9c85b', '1', '1', '498\n']
['87068', '4', '-1', '0', '0.916999995708465', '0.9608271718025208', 'ANDROID', '33', 'aa27f680-2ddb-4d61-b685-e29a15f9c85b', '0', '1', '498\n']

Q.1 如何将这个数组的部分元素转换成整数?

Q.2 如何删除第一行第一个元素中的“\ufeff”?

Q.3 如何删除数组最后一个元素中的\n?我正在对最后一个元素使用替换功能。

【问题讨论】:

  • 第一季度,int(str_value_to_convert)。第二季度/第三季度。 .replace.strip。不带参数的剥离将删除字符串开头和结尾的所有空格,包括\n
  • 另外:您打印的是line,而不是d,因此您无需替换即可看到内容。 ;) 你的.replace('\n', '') 是正确的。
  • \ufeff 表示 BOM - Byte Order Mark

标签: python arrays arraylist type-conversion


【解决方案1】:

虽然您可以检查子字符串中的每个字符isdigit,还是仅将try 转换为int,但我建议不要这样做。如果出于某种原因应该保留字符串的段也只包含数字怎么办?另外,请注意,您还有可能需要转换为float 的部分。 相反,我建议使用类型列表来确定每个部分应如何转换,然后 ziping 两者并进行实际转换。

>>> line = '\ufeff87068,4,-1,0,0.916999995708465,0.9608271718025208,ANDROID,33,aa27f680-2ddb-4d61-b685-e29a15f9c85b,1,1,498\n'
>>> items_raw = line.strip().lstrip('\ufeff').split(",")
>>> types = [int, int, int, int, float, float, str, int, str, int, int, int]
>>> items = [t(x) for t, x in zip(types, items_raw)]    
>>> items
[87068, 4, -1, 0,
 0.916999995708465, 0.9608271718025208,
 'ANDROID',
 33,
 'aa27f680-2ddb-4d61-b685-e29a15f9c85b',
 1, 1, 498]

您还可以在列表上使用乘法来使 types 列表更短一些,并且可能更具可读性,尤其是当列表中有更多条目时:

types = [int] * 4 + [float] * 2 + [str, int, str] + [int] * 3

同样,您可以为字段名称创建另一个列表,并zip它们与字典理解中的项目:

>>> fields = ["customer_id","listing_slot","closingIn","new_user","last_mile_distance","stress","customer_user_agent","listing_restaurant_sla","request_id","ld","city_id","restaurant_id"]
>>> d = {f: x for f, x in zip(fields, items)}

或者将它与单个字典理解中的类型转换结合起来:

>>> d = {f: t(x) for f, t, x in zip(fields, types, items_raw)}

无论哪种方式,d 最终都是

{'city_id': 1,
 'closingIn': -1,
 'customer_id': 87068,
 'customer_user_agent': 'ANDROID',
 'last_mile_distance': 0.916999995708465,
 'ld': 1,
 'listing_restaurant_sla': 33,
 'listing_slot': 4,
 'new_user': 0,
 'request_id': 'aa27f680-2ddb-4d61-b685-e29a15f9c85b',
 'restaurant_id': 498,
 'stress': 0.9608271718025208}

【讨论】:

  • 您好,谢谢您的回复。我还想添加请求参数的名称,以便在 API 调用中传递它们。我无法理解我可以在哪里添加它们。在我的原始代码中,我添加了 d = {"customer_id": line[0],......
  • 目前我的输出是:[87068, 4, -1, 0, 0.916999995708465, 0.9608271718025208, 'ANDROID', 33, 'aa27f680-2ddb-4d61-b685-e29a15f9c85b', , 498] {"errorCode":"Exception","errorBody":{},"status":0} 但是,我希望请求类似于 {"rdc_name": 87068, "listing_slot" : 4, "closingIn" :-1,.......
【解决方案2】:

我的输出是:

您打印的是line,而不是d,因此您无需替换即可看到内容。 ;) 你的.replace('\n', '') 是正确的。


第二季度/第三季度。是的。您可以使用.replace.strip。不带参数的剥离将删除字符串开头和结尾的所有空格,包括\n

如果你用这个替换你的简单拆分:

line = [elem.strip().replace('\ufeff', '') for elem in line.split(',')]

确保没有元素在开头和结尾有空格,并且没有元素有这个 unicode 字符。


第一季度。这是int(str_value_to_convert)(所以int(line[0]等等)。

但要不要在里面放这么多int(),你可以使用这一行:

line = [int(elem) if elem.isdigit() or (elem[0] == '-' and elem[1:].isdigit()) else elem for elem in line]

.isdigit() 检查字符串中的所有字符是否都是数字。不适用于负整数(因为- 不是数字),所以我制作了or,检查第一个字符是否为减号以及字符串的其余部分是否为数字。


另一个有用的变化是您创建字典的方式。因为您按顺序使用来自line 的元素,所以我们可以将其与标签列表一起压缩并使用显式dict 构造函数:

for cnt, line in enumerate(fp):
    line = [elem.strip().replace('\ufeff', '') for elem in line.split(',')]
    line = [int(elem) if elem.isdigit() or (elem[0] == '-' and elem[1:].isdigit()) else elem for elem in line]
    d = dict(zip(["customer_id","listing_slot","closingIn","new_user","last_mile_distance","stress","customer_user_agent","listing_restaurant_sla","request_id","ld","city_id","restaurant_id"], line)) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-16
    • 2013-08-14
    • 1970-01-01
    • 2015-09-03
    • 2014-12-02
    • 2017-09-26
    • 1970-01-01
    • 2013-12-02
    相关资源
    最近更新 更多