![](/img/trans.png)
[英]Python : How to print new line after using end="" in for loop?
[英]How to print a fail statement only after reaching end of loop in Python?
我有一個小代碼片段,需要幫助實現一個失敗語句( No match
)。 這是片段:
for row in reader:
# converts each string num --> int num
i = 1
while i < len(row):
row[i] = int(row[i])
i += 1
if STR_count_large(sequence) == row[1:]:
print(row[0])
if STR_count_small(sequence) == row[1:]:
print(row[0])
我遍歷名為reader
的csv
文件中的每一row
,並將該行中的每個元素從字符串轉換為 int。 之后,我將該特定行的列表內容(從第一個元素到末尾)與兩個函數進行比較,每個函數都包含一個列表。 如果兩個列表匹配,我打印row[0]
,它只包含匹配列表所屬的人的姓名。 但是,如果這兩個if
語句在通過for row in reader:
后都失敗了,我將如何 go 關於僅打印一次像No match
這樣的語句? 因為如果我把它寫在循環中,這條語句將被打印row
數而不是一次。
編輯:這是我使用 bschlueter 的想法的(不成功的)實現。 任何幫助將不勝感激:
exceptions = list()
for row in reader:
# converts each string num --> int num
i = 1
while i < len(row):
row[i] = int(row[i])
i += 1
try:
if STR_count_large(sequence) == row[1:]:
print(row[0])
if STR_count_small(sequence) == row[1:]:
print(row[0])
except (STR_count_large(sequence) != row[1:] and STR_count_small(sequence) != row[1:]) as exception:
exceptions.append(exception)
if exceptions:
print("No match")
您可以累積錯誤,然后在循環完成后檢查累積:
exceptions = list()
for row in reader:
try:
do_a_thing(row)
except MyException as exception:
exceptions.append(exception)
# Do something if any exceptions were added to the list
if exceptions:
handle_exceptions(exceptions)
只需再添加一個帶有 and 的 if 語句來捕獲和打印不匹配。 在第二個 IF 語句的末尾添加這個
if row == reader[len(reader)]:#Check for last iteration
if STR_count_large(sequence) != row[1:]: and STR_count_small(sequence) != row[1:]:
print("No Match")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.