编写一个程序,请找出1000内可以被7整除,但不能是5的倍数的数。获得的数字应以逗号分隔的顺序存放在列表中。分别以 while , for ,列表推导式,生成器推导式的方式来实现。
时间: 2024-05-10 21:17:18 浏览: 16
使用while循环实现:
```
i = 0
result = []
while i < 1000:
i += 1
if i % 7 == 0 and i % 5 != 0:
result.append(i)
print(','.join(map(str, result)))
```
使用for循环实现:
```
result = []
for i in range(1, 1000):
if i % 7 == 0 and i % 5 != 0:
result.append(i)
print(','.join(map(str, result)))
```
使用列表推导式实现:
```
result = [i for i in range(1, 1000) if i % 7 == 0 and i % 5 != 0]
print(','.join(map(str, result)))
```
使用生成器推导式实现:
```
result = (i for i in range(1, 1000) if i % 7 == 0 and i % 5 != 0)
print(','.join(map(str, result)))
```
相关问题
编写一个程序,请找出1000内可以被7整除,但不能是5的倍数的数。获得的数字应以逗号分隔的顺序存放在列表中分别以while,for,列表推导式,生成器推导式的方式实现
以下是分别使用while、for、列表推导式和生成器推导式实现的程序:
使用while:
```
numbers = []
n = 1
while n <= 1000:
if n % 7 == 0 and n % 5 != 0:
numbers.append(n)
n += 1
print(numbers)
```
使用for:
```
numbers = []
for n in range(1, 1001):
if n % 7 == 0 and n % 5 != 0:
numbers.append(n)
print(numbers)
```
使用列表推导式:
```
numbers = [n for n in range(1, 1001) if n % 7 == 0 and n % 5 != 0]
print(numbers)
```
使用生成器推导式:
```
numbers = (n for n in range(1, 1001) if n % 7 == 0 and n % 5 != 0)
print(list(numbers))
```
这四种方式都可以得到相同的结果,即1000内可以被7整除,但不能是5的倍数的数的列表。
编写一个shell脚本,找出100以内所有能被3整除的数,每行显示7个数,然后换行显示
好的,以下是一个实现的示例:
```
#!/bin/bash
# 循环 1 到 100
for i in {1..100}; do
# 如果是 3 的倍数
if [ $((i % 3)) -eq 0 ]; then
# 输出当前数
printf '%-4d' $i
# 如果当前行已经显示了 7 个数,则换行
if [ $((i % 21)) -eq 0 ]; then
echo
fi
fi
done
# 最后一行也要换行
echo
```
以上脚本使用了 `for` 循环遍历 1 到 100 的数,然后使用取模运算判断当前数是否是 3 的倍数,并使用 `printf` 函数输出当前数。同时,使用 `if` 判断是否需要换行,每行显示 7 个数。
你可以将其保存为一个文件,比如 "threes.sh",然后在终端中运行:
```
$ bash threes.sh
```
输出结果应该类似于:
```
3 6 9 12 15 18 21
24 27 30 33 36 39 42
45 48 51 54 57 60 63
66 69 72 75 78 81 84
87 90 93 96 99
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)