C 到 Python :For 循环
C to Python : For loop
所以我在 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
代码相同的逻辑,这意味着 j
将从 i
:
开始
A = [1,2,3,4,5]
for i in range(len(A)):
for j in range(i, len(A)):
try:
print(A[i],A[j+1])
except IndexError:
pass
另一个优雅的解决方案是使用 itertools
模块:
from itertools import combinations
A = [1,2,3,4,5]
comb = combinations(A, 2)
for c in comb:
print(c)
这不是这样做的方式:
- try / except 块很昂贵,这里实际上不需要它们
- for 的形式不是很 Pythonic
您应该尝试尽可能接近地复制 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
所以我在 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
代码相同的逻辑,这意味着 j
将从 i
:
A = [1,2,3,4,5]
for i in range(len(A)):
for j in range(i, len(A)):
try:
print(A[i],A[j+1])
except IndexError:
pass
另一个优雅的解决方案是使用 itertools
模块:
from itertools import combinations
A = [1,2,3,4,5]
comb = combinations(A, 2)
for c in comb:
print(c)
这不是这样做的方式:
- try / except 块很昂贵,这里实际上不需要它们
- for 的形式不是很 Pythonic
您应该尝试尽可能接近地复制 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