2

## [python]輸出超過字數換行

8 9 12 16 18 20 24 27 28 32 36 40 44 45 48 52 54

8 9 12 16 18 20 24 27 28 32
36 40 44 45 48 52 54

### 5 個回答

4

iT邦研究生 5 級 ‧ 2020-06-14 20:24:28

``````a = int(input())
b = int(input())
list1 = []
cnt = 0 # 設定一個計數器
for i in range(a, b+1):
if i%4==0 or i%9==0:
print(str(i).ljust(4), end='')
list1 += [i]
cnt += 1
if cnt == 10:
print() #當計數器累積到10個時(即40個字元)，換行
cnt = 0 #計數器歸零

print('\t')
print(len(list1))
print(sum(list1))
``````

lydia0231 iT邦新手 5 級 ‧ 2020-06-14 20:39:25 檢舉

1

iT邦大神 1 級 ‧ 2020-06-14 20:27:46
``````            list1+=[i]
``````

``````            list1+=[i]
if len(list1)%10==0:
print("")
``````
lydia0231 iT邦新手 5 級 ‧ 2020-06-14 20:40:52 檢舉

lydia0231 iT邦新手 5 級 ‧ 2020-06-14 21:14:14 檢舉

if len(list1)%10==0:
print("")

1

iT邦新手 5 級 ‧ 2020-06-14 21:55:47

``````a = int(input())
b = int(input())

num = list(x for x in range(a, b+1))
count = 0
num_list = list()
for i in num:
if i%4==0 or i%9==0:
if count<9 or count>9:
num_list.append(i)
print(i, '...', sep='', end='')
count += 1
elif count==9: #用一下上面大大的方法 elif len(num_list)==10:
print(i, '...', sep='', end='\n')
num_list.append(i)
count += 1

print(f"\n{count}")
print(sum(num_list))
``````
3

iT邦大師 1 級 ‧ 2020-06-14 22:10:33
``````#!/usr/bin/env python3

str1 = '8   9   12  16  18  20  24  27  28  32  36  40  44  45  48  52  54'
chunk_size = 40
result = [str1[y - chunk_size: y] for y in range(chunk_size, len(str1)+chunk_size, chunk_size)]
print(*result, sep='\n')
``````

lydia0231 iT邦新手 5 級 ‧ 2020-06-15 20:38:16 檢舉

2
froce
iT邦大師 1 級 ‧ 2020-06-15 11:22:25

``````a = 5
b = 55
countResult = [x for x in range(a, b+1) if x % 4 == 0 or x % 9 == 0]
strResult = ["{}   ".format(str(i))[:4] for i in countResult]
[print(x, end="") if i % 9 != 0 or i == 0 else print(x) for i, x in enumerate(strResult)]
``````

enumerate()很好用，會傳回可疊代物件的索引和元素。

``````countResult = [8, 9, 12, 16, 18, 20, 24, 27, 28, 32, 36, 40, 44, 45, 48, 52, 54]
for i, x in enumerate(countResult):
if i % 9 != 0 or i == 0:
print("{}   ".format(str(x))[:4], end="")
else:
print("{}   ".format(str(x))[:4])
``````

python 真是奇妙的語言

``````[print(x, end="") if i % 9 != 0 or i == 0 else print(x) for i, x in enumerate(strResult)]
``````

froce iT邦大師 1 級 ‧ 2020-06-15 11:59:07 檢舉

``````countResult = [x for x in range(a, b+1) if x % 4 == 0 or x % 9 == 0]
``````

list comprehension只適合for只有一、二層的時候，太多層乖乖寫for或拿出來當函式。

lydia0231 iT邦新手 5 級 ‧ 2020-06-15 20:40:52 檢舉