遍历set集合每行输出5个换行
时间: 2024-05-03 14:17:59 浏览: 16
可以这样实现:
```python
s = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
count = 0
for item in s:
print(item, end=" ")
count += 1
if count == 5:
print()
count = 0
```
输出结果为:
```
1 2 3 4 5
6 7 8 9 10
```
相关问题
遍历set集合,输出所有元素,用空格隔开,末尾换行,用c++
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct _set {
int *data;
int size;
} Set;
Set *createSet(int size) {
Set *set = (Set *)malloc(sizeof(Set));
set->data = (int *)malloc(sizeof(int) * size);
set->size = size;
return set;
}
void insert(Set *set, int num) {
for (int i = 0; i < set->size; i++) {
if (set->data[i] == num) {
return;
}
if (set->data[i] == 0) {
set->data[i] = num;
return;
}
}
}
void traverse(Set *set) {
for (int i = 0; i < set->size; i++) {
if (set->data[i] != 0) {
printf("%d ", set->data[i]);
}
}
printf("\n");
}
int main() {
Set *set = createSet(10);
insert(set, 1);
insert(set, 2);
insert(set, 3);
insert(set, 4);
insert(set, 5);
traverse(set);
return 0;
}
set集合遍历之后输出所有元素,用空格隔开,末尾换行
假设给定的集合为set_a,则可以使用以下代码实现:
```python
set_a = {1, 2, 3, 4, 5}
for element in set_a:
print(element, end=' ')
print() # 输出换行符
```
输出结果为:
```
1 2 3 4 5
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)