作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
> a = [1, 2, 3, 4, 5] >>> >>> -6ren">
所以我在 C 中有这段代码,它输出以下内容:
代码:
scanf("%ld",&N);
long long A[N];
for(i=1;i<=N;i++)
scanf("%lld", &A[i]);
for(i=1;i<N;i++)
for(j=i;j<=N-1;j++) {
printf("%d %d\n", A[i], A[j+1]);
输入:
5
1 2 3 4 5
输出:
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
如何使用 python 3.7.x 获得相同的输出?
尝试过:
A = [1,2,3,4,5]
for i in range(len(A)):
for j in range(len(A)):
try:
print(A[i],A[j+1])
except IndexError:
pass
尝试输出:
1 2
1 3
1 4
1 5
2 2
2 3
2 4
2 5
3 2
3 3
3 4
3 5
4 2
4 3
4 4
4 5
5 2
5 3
5 4
5 5
这是我得到的输出,它只是遍历每个循环,打印出值,从而得到重复的对。
感谢帮助,谢谢!
最佳答案
这不是这样做的方式:
您应该尝试尽可能接近地复制 C 循环。为此,[Python 3. Docs]: Built-in Functions - enumerate(iterable, start=0)派上用场(允许处理元素索引)。此外,还使用了序列切片。
>>> a = [1, 2, 3, 4, 5]
>>>
>>> for idx0, elem0 in enumerate(a):
... for elem1 in a[idx0 + 1:]:
... print(f"{elem0} {elem1}")
...
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
关于python - C 到 Python : For loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59318253/
我是一名优秀的程序员,十分优秀!