TypeError:序列项0:预期的字符串,找到的int

问题:TypeError:序列项0:预期的字符串,找到的int

我正在尝试将字典中的数据插入数据库。我想遍历值并根据数据类型对它们进行相应的格式化。这是我正在使用的代码的片段:

def _db_inserts(dbinfo):
    try:
        rows = dbinfo['datarows']

        for row in rows:
            field_names = ",".join(["'{0}'".format(x) for x in row.keys()])
            value_list = row.values()

            for pos, value in enumerate(value_list):
                if isinstance(value, str):
                    value_list[pos] = "'{0}'".format(value)
                elif isinstance(value, datetime):
                    value_list[pos] = "'{0}'".format(value.strftime('%Y-%m-%d'))

            values = ",".join(value_list)

            sql = "INSERT INTO table_foobar ({0}) VALUES ({1})".format(field_names, values)

    except Exception as e:
        print 'BARFED with msg:',e

当我使用一些示例数据运行算法(见下文)时,出现错误:

TypeError:序列项0:预期的字符串,找到的int

出现上述错误的value_list数据示例如下:

value_list = [377, -99999, -99999, 'f', -99999, -99999, -99999, 1108.0999999999999, 0, 'f', -99999, 0, 'f', -99999, 'f', -99999, 1108.0999999999999, -99999, 'f', -99999, 'f', -99999, 'f', 'f', 0, 1108.0999999999999, -99999, -99999, 'f', 'f', 'f', -99999, 'f', '1984-04-02', -99999, 'f', -99999, 'f', 1108.0999999999999] 

我究竟做错了什么?

I am attempting to insert data from a dictionary into a database. I want to iterate over the values and format them accordingly, depending on the data type. Here is a snippet of the code I am using:

def _db_inserts(dbinfo):
    try:
        rows = dbinfo['datarows']

        for row in rows:
            field_names = ",".join(["'{0}'".format(x) for x in row.keys()])
            value_list = row.values()

            for pos, value in enumerate(value_list):
                if isinstance(value, str):
                    value_list[pos] = "'{0}'".format(value)
                elif isinstance(value, datetime):
                    value_list[pos] = "'{0}'".format(value.strftime('%Y-%m-%d'))

            values = ",".join(value_list)

            sql = "INSERT INTO table_foobar ({0}) VALUES ({1})".format(field_names, values)

    except Exception as e:
        print 'BARFED with msg:',e

When I run the algo using some sample data (see below), I get the error:

TypeError: sequence item 0: expected string, int found

An example of a value_list data which gives the above error is:

value_list = [377, -99999, -99999, 'f', -99999, -99999, -99999, 1108.0999999999999, 0, 'f', -99999, 0, 'f', -99999, 'f', -99999, 1108.0999999999999, -99999, 'f', -99999, 'f', -99999, 'f', 'f', 0, 1108.0999999999999, -99999, -99999, 'f', 'f', 'f', -99999, 'f', '1984-04-02', -99999, 'f', -99999, 'f', 1108.0999999999999] 

What am I doing wrong?


回答 0

string.join 连接字符串列表内的元素,而不是整数。

使用此生成器表达式代替:

values = ','.join(str(v) for v in value_list)

string.join connects elements inside list of strings, not ints.

Use this generator expression instead :

values = ','.join(str(v) for v in value_list)

回答 1

尽管给出的列表理解/生成器表达式答案是可以的,但我发现这更易于阅读和理解:

values = ','.join(map(str, value_list))

Although the given list comprehension / generator expression answers are ok, I find this easier to read and understand:

values = ','.join(map(str, value_list))

回答 2

更换

values = ",".join(value_list)

values = ','.join([str(i) for i in value_list])

要么

values = ','.join(str(value_list)[1:-1])

Replace

values = ",".join(value_list)

with

values = ','.join([str(i) for i in value_list])

OR

values = ','.join(str(value_list)[1:-1])

回答 3

cvalPriyank Patel的答案非常有用。但是,请注意,某些值可能是unicode字符串,因此可能导致str抛出UnicodeEncodeError错误。在这种情况下,请用功能替换str功能unicode

例如,假定字符串Libië(利比亚语的荷兰语),在Python中表示为unicode字符串u'Libi\xeb'

print str(u'Libi\xeb')

引发以下错误:

Traceback (most recent call last):
  File "/Users/tomasz/Python/MA-CIW-Scriptie/RecreateTweets.py", line 21, in <module>
    print str(u'Libi\xeb')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 4: ordinal not in range(128)

但是,以下行不会引发错误:

print unicode(u'Libi\xeb') # prints Libië

因此,请替换:

values = ','.join([str(i) for i in value_list])

通过

values = ','.join([unicode(i) for i in value_list])

为了安全。

The answers by cval and Priyank Patel work great. However, be aware that some values could be unicode strings and therefore may cause the str to throw a UnicodeEncodeError error. In that case, replace the function str by the function unicode.

For example, assume the string Libië (Dutch for Libya), represented in Python as the unicode string u'Libi\xeb':

print str(u'Libi\xeb')

throws the following error:

Traceback (most recent call last):
  File "/Users/tomasz/Python/MA-CIW-Scriptie/RecreateTweets.py", line 21, in <module>
    print str(u'Libi\xeb')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 4: ordinal not in range(128)

The following line, however, will not throw an error:

print unicode(u'Libi\xeb') # prints Libië

So, replace:

values = ','.join([str(i) for i in value_list])

by

values = ','.join([unicode(i) for i in value_list])

to be safe.


回答 4

字符串插值是一种传递格式化字符串的好方法。

values = ', '.join('$%s' % v for v in value_list)

String interpolation is a nice way to pass in a formatted string.

values = ', '.join('$%s' % v for v in value_list)


回答 5

您可以先将整数数据帧转换为字符串,然后执行操作,例如

df3['nID']=df3['nID'].astype(str)
grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))

you can convert the integer dataframe into string first and then do the operation e.g.

df3['nID']=df3['nID'].astype(str)
grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))