簡體   English   中英

將字符串插入整數列表

[英]Inserting a string into a list of integers

我正在嘗試編寫一個腳本,在給定數字的所有奇數位之間插入一個“-”(即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

追溯(最近一次通話):

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

print DashInsert(string)

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

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

TypeError:在字符串格式化期間並非所有參數都已轉換

您可以通過正則表達式執行此操作。

>>> import re
>>> s = 991453
>>> re.sub(r'(?<=[13579])(?=[13579])', r'-', str(s))
'9-9-145-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)

您的錯誤是因為您正在修改要迭代的列表。 當您在列表中插入- ,它將成為%的目標,並且您會遇到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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM