【问题标题】:Inserting a string into a list of integers将字符串插入整数列表
【发布时间】:2015-02-28 04:55:42
【问题描述】:

我正在尝试制作一个脚本,其中在给定数字的所有奇数之间放置一个“-”(即 991453 将是 9-9-145-3),但由于某种原因 python 不允许我插入一个 str 到一个整数列表中。我不断收到的错误是“TypeError:并非所有参数都在字符串格式化期间转换”

我的代码:

def DashInsert(text):

    list_int = map(int, list(text))

    for i in xrange(len(list_int)-1):
        if (list_int[i] % 2 == 1) and (list_int[i+1] % 2 == 1):
           print i
           list_int.insert(i+1,'-')

    return list_int

这是我的实际输入和错误:

999472

0

Traceback(最近一次调用最后一次):

文件“DashInsert.py”,第 17 行,在

print DashInsert(string)

文件“DashInsert.py”,第 11 行,在 DashInsert 中

if (list_int[i] % 2 == 1) and (list_int[i+1] % 2 == 1):

TypeError:字符串格式化期间并非所有参数都转换

【问题讨论】:

  • 请显示实际输入和实际错误回溯。
  • 仅供参考,这是因为您正在修改(特别是添加到)列表在迭代列表时。这几乎从来都不是一个好主意。我的意思是,看看你在做什么。首先将所有内容都转换为整数,然后找到所需的整数,然后在下一个位置插入 a string。因此,下一轮你的% 是字符串格式!
  • @Two-BitAlchemist 我明白你在说什么,但是 if 语句不应该允许插入的“-”通过对吗?所以我不明白为什么它不起作用
  • 什么?插入发生在 if 语句内部。 '-' 可以在该表达式的计算结果为真时插入。

标签: python list type-conversion


【解决方案1】:

您的错误是因为您正在修改您正在迭代的列表。当您将- 插入到列表中时,它将成为% 的目标,并且您会得到一个TypeError。

在Python中,%是一个字符串格式化操作符,'-'是一个字符串;这就是为什么你得到一个不太清楚的错误:

>>> '-' % 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

对于字符串,您可以这样使用%

>>> 'x %s y %s %i' % ('and', 'is', 13)
'x and y is 13'

对您的代码的修复是附加到一个单独的列表:

def DashInsert(s):

    list_int = map(int, s)

    rtr=[]

    for i, e in enumerate(list_int[0:-1]):
        rtr.append(str(e))
        if e % 2 == 1 and list_int[i+1] % 2 == 1:
           rtr.append('-')
    rtr.append(str(list_int[-1]))    

    return rtr

【讨论】:

  • 这太棒了,这正是我所需要的,我理解你为什么使用 i 作为列表的索引而使用 e 作为列表的变量。不过,一个快速的问题是,在您的 for 循环中,为什​​么 python 使用 i 作为索引而使用 e 作为变量?看起来 i 和 e 都是枚举列表的变量,如果这是一个愚蠢的问题,对不起。
  • 根本不是一个愚蠢的问题! enumerate 的返回是一个元组,其中包含序列中的索引以及该序列中具有该索引号的项目(如果序列支持索引,则并非全部都支持)。当我拥有for i, e in enumerate(seq) 时,它会将两个成员元组解压缩到 i 和 e 中。清除吗?
【解决方案2】:

你可以通过正则表达式来做到这一点。

>>> import re
>>> s = 991453
>>> re.sub(r'(?<=[13579])(?=[13579])', r'-', str(s))
'9-9-145-3'

【讨论】:

  • 您能解释一下代码中的 r'(?
  • 因为这是家庭作业,而且显然是针对低级 CS 课程,所以不用担心他的代码的那部分。它被称为regular expression,稍后您将在更高级别的 CS 课程中接触到它们,这些课程会涉及到它背后的数学。基本上,即使您不知道它到底会说什么,它们也可以让您按模式描述字符串。如果您必须在没有导入的情况下执行此操作,您的代码将起作用,但不要在迭代时修改列表。相反,请写下连字符的位置,然后再将它们插入。
【解决方案3】:

我怀疑这是很糟糕的代码,但它确实有效-

number = 991453

number_list = []
for i, item in enumerate(str(number)):
    try:
        if int(item) % 2 != 0 and int(str(number)[i + 1]) % 2 != 0:
            number_list.append(item + '-')
        else:
            number_list.append(item)
    except:
        number_list.append(item)
print(''.join(number_list))

编辑:实际上,没有必要列一个清单,所以我们可以这样做-

number = 991453

dash_number = ''
for i, item in enumerate(str(number)):
    try:
        if int(item) % 2 != 0 and int(str(number)[i + 1]) % 2 != 0:
            dash_number += item + '-'
        else:
            dash_number += item
    except:
        dash_number += item
print(dash_number)

编辑:以下是不使用 try/except 的方法。

number = 991453

dash_number = ''
for i, item in enumerate(str(number)[:-1]):
    if int(item) % 2 != 0 and int(str(number)[i + 1]) % 2 != 0:
        dash_number += item + '-'
    else:
        dash_number += item
dash_number += str(number)[-1]

print(dash_number)

【讨论】:

    猜你喜欢
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    相关资源
    最近更新 更多