所以我需要通過一個回圈并在矩陣行內的每個元素中應用條件陳述句。需要檢查的條件:
- 元素是否是字母,如果是,則附加它,如果不是,則進行下一個條件檢查
- 下一個檢查應該檢查它的符號/非字母和它的下一個元素(我用于
j 1索引)是否也是符號/非字母,如果這是真的,那么附加一個''(一個空格)。但是當我運行它時,由于每行的最后一個元素無法訪問j 1索引,它會偶然發現“串列索引超出范圍”錯誤。然后,我創建了另一個預回圈來檢查元素是否是最后一個元素。如果它的最后一個元素進入下一個回圈進行簡單檢查。
clinput2=[['T', 'h', 'i', 's', '$', '#', 'i'],
['s', '%', ' ', 'S', 'p', 'a', 'r'],
['t', 'a', '#', ' ', ' ', '%', '!']]
for j in range(len(clinput2[0])):
# print (clinput2[i][j])
if (clinput2[i][j].isalpha()):
cara.append(clinput2[i][j])
elif (not clinput2[i][j].isalpha() ):
if j 1<len(clinput2[i]):
if (not clinput2[i][j 1].isalpha() or clinput2[i][j 1]==' '):
cara.append(' ')
j =1
elif (not clinput2[i][j].isalpha() or clinput2[i][j]==' '):
pass
所需的輸出:This is Sparta
那么如果沒有 if 陳述句,我該怎么做呢?,現在我可以用 if 陳述句來做到這一點,但要求是不要使用 if 陳述句。
我嘗試了這種條件陳述句,但找不到嵌套條件的方法,在引數中傳遞函式會太臟太長:
['pass', cara.append(clinput2[i][j])][clinput2[i][j].isalpha()]
原來的方法:
print ["no", "yes"][x > y]
如果沒有 if 陳述句,我該怎么做?
uj5u.com熱心網友回復:
借助正則運算式,我們可以輕松避免條件陳述句。尤其是,
import re
clinput2=[['T', 'h', 'i', 's', '$', '#', 'i'],
['s', '%', ' ', 'S', 'p', 'a', 'r'],
['t', 'a', '#', ' ', ' ', '%', '!']]
mat_str = ''.join(c for row in clinput2 for c in row)
print(re.sub(r'[^a-zA-Z] ',' ',a))
mat_str是按順序連接矩陣所有行的所有字符形成的字串。該運算式r'[^a-zA-Z] '匹配任何連續的非字母字符字串,并且子函式將每個這樣的字串替換為一個空格,' '.
uj5u.com熱心網友回復:
只需使用一個可怕的條件。
import itertools
clinput2 = [['T', 'h', 'i', 's', '$', '#', 'i'],
['s', '%', ' ', 'S', 'p', 'a', 'r'],
['t', 'a', '#', ' ', ' ', '%', '!']]
clinput2 = list(itertools.chain(*clinput2))
output = ''
for char, next_char in itertools.zip_longest(clinput2, clinput2[1:]):
output = (
(char.isalpha() and char) or
(not char.isalpha() and next_char is not None and not next_char.isalpha() and ' ') or
(''))
print(output)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/529294.html
標籤:Python循环if 语句矩阵
上一篇:嵌套回圈提供了不需要的操作
