亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 中不允許使用前導零?

Python 中不允許使用前導零?

弒天下 2023-03-22 16:13:44
我有一個代碼用于查找列表中給定字符串的可能組合。但是面臨前導零的問題,如SyntaxError: leading zeros in decimal integer literals is not allowed; 對八進制整數使用 0o 前綴。如何解決這個問題,因為我想傳遞帶有前導零的值(不能一直手動編輯值)。下面是我的代碼def permute_string(str):    if len(str) == 0:        return ['']    prev_list = permute_string(str[1:len(str)])    next_list = []    for i in range(0,len(prev_list)):        for j in range(0,len(str)):            new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1]            if new_str not in next_list:                next_list.append(new_str)    return next_listlist = [129, 831 ,014]length = len(list)i = 0# Iterating using while loopwhile i < length:    a = list[i]    print(permute_string(str(a)))    i += 1;
查看完整描述

2 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

由于歧義,以 0 開頭的整數文字在 python 中是非法的(顯然除了零本身)。以 0 開頭的整數文字具有以下字符,用于確定它屬于哪個數字系統:0x十六進制、0o八進制、0b二進制。


至于整數本身,它們只是數字,數字永遠不會從零開始。如果你有一個表示為字符串的整數,并且它恰好有一個前導零,那么當你將它轉換為整數時它會被忽略:


>>> print(int('014'))

14

考慮到你在這里要做的事情,我只是重寫列表的初始定義:


lst = ['129', '831', '014']

...

while i < length:

    a = lst[i]

    print(permute_string(a))  # a is already a string, so no need to cast to str()

或者,如果您需要lst成為一個整數列表,那么您可以使用格式字符串文字而不是調用來更改將它們轉換為字符串的方式str(),這允許您用零填充數字:


lst = [129, 831, 14]

...

while i < length:

    a = lst[i]

    print(permute_string(f'{a:03}'))  # three characters wide, add leading 0 if necessary

在這個答案中,我使用lst作為變量名,而不是list你問題中的。你不應該使用list作為變量名,因為它也是代表內置列表數據結構的關鍵字,如果你命名一個變量那么你就不能再使用關鍵字。


查看完整回答
反對 回復 2023-03-22
?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

最后,我得到了答案。下面是工作代碼。


def permute_string(str):

    if len(str) == 0:

        return ['']

    prev_list = permute_string(str[1:len(str)])

    next_list = []

    for i in range(0,len(prev_list)):

        for j in range(0,len(str)):

            new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1]

            if new_str not in next_list:

                next_list.append(new_str)

    return next_list


#Number should not be with leading Zero

actual_list = '129, 831 ,054, 845,376,970,074,345,175,965,068,287,164,230,250,983,064'

list = actual_list.split(',')

length = len(list)

i = 0


# Iterating using while loop

while i < length:

    a = list[i]

    print(permute_string(str(a)))

    i += 1;


查看完整回答
反對 回復 2023-03-22
  • 2 回答
  • 0 關注
  • 215 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號