두 개의 변수가있는 "for 루프"?
동일한 for
루프 에 두 개의 변수를 포함하려면 어떻게 해야합니까?
t1 = [a list of integers, strings and lists]
t2 = [another list of integers, strings and lists]
def f(t): #a function that will read lists "t1" and "t2" and return all elements that are identical
for i in range(len(t1)) and for j in range(len(t2)):
...
중첩 된 for 루프의 효과를 원하면 다음을 사용하십시오.
import itertools
for i, j in itertools.product(range(x), range(y)):
# Stuff...
동시에 반복하려면 다음을 사용하십시오.
for i, j in zip(range(x), range(y)):
# Stuff...
경우에 유의 x
과 y
같은 길이 아닌, zip
짧은 목록에 자릅니다. @abarnert가 지적했듯이 가장 짧은 목록으로 자르지 않으려면 itertools.zip_longest
.
최신 정보
"목록"t1 "및"t2 "를 읽고 동일한 모든 요소를 반환하는 함수"에 대한 요청에 따라 OP가 zip
또는 product
. 나는 그들이 원한다고 생각한다 set
:
def equal_elements(t1, t2):
return list(set(t1).intersection(set(t2)))
# You could also do
# return list(set(t1) & set(t2))
a의 intersection
메소드는 set
그것과 다른 세트에 공통된 모든 요소를 반환합니다 (목록에 다른 list
s 가 포함되어있는 경우 내부 list
를 tuples
첫 번째 로 변환하여 해시 가능하도록 할 수 있습니다. 그렇지 않으면에 대한 호출 set
이 실패합니다.) list
함수는리스트로 설정 다시 켜집니다.
업데이트 2
또는 OP 는 목록에서 동일한 위치에 동일한 요소를 원할 수 있습니다 . 이 경우 zip
가장 적절할 것이며 가장 짧은 목록으로 잘리는 것은 원하는 것입니다 (목록 중 하나가 5 개 요소 만 있으면 인덱스 9에 동일한 요소가있을 수 없기 때문입니다). . 그것이 당신이 원하는 것이라면 다음과 같이 가십시오.
def equal_elements(t1, t2):
return [x for x, y in zip(t1, t2) if x == y]
그러면 목록에서 동일하고 동일한 위치에있는 요소 만 포함 된 목록이 반환됩니다.
여기에는 두 가지 가능한 질문이 있습니다. 어떻게 이러한 변수를 동시에 반복 할 수 있는지 또는 어떻게 조합 을 반복 할 수 있는지 입니다.
다행히도 둘 다에 대한 간단한 답이 있습니다. 첫 번째 경우에는 zip
.
x = [1, 2, 3]
y = [4, 5, 6]
for i, j in zip(x, y):
print(str(i) + " / " + str(j))
출력됩니다
1 / 4
2 / 5
3 / 6
모든 iterable을 에 넣을 수 zip
있으므로 다음과 같이 예제를 쉽게 작성할 수 있습니다.
for i, j in zip(range(x), range(y)):
# do work here.
사실, 그것이 작동하지 않는다는 것을 깨달았습니다. 더 작은 범위가 다 떨어질 때까지만 반복됩니다. 어떤 경우에는 루프 조합을 반복하려는 것처럼 들립니다.
다른 경우에는 중첩 루프를 원할뿐입니다.
for i in x:
for j in y:
print(str(i) + " / " + str(j))
당신에게 준다
1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...
목록 이해력으로도 할 수 있습니다.
[str(i) + " / " + str(j) for i in range(x) for j in range(y)]
Hope that helps.
Any reason you can't use a nested for loop?
for i in range(x):
for j in range(y):
#code that uses i and j
for (i,j) in [(i,j) for i in range(x) for j in range(y)]
should do it.
If you really just have lock-step iteration over a range, you can do it one of several ways:
for i in range(x):
j = i
…
# or
for i, j in enumerate(range(x)):
…
# or
for i, j in ((i,i) for i in range(x)):
…
All of the above are equivalent to for i, j in zip(range(x), range(y))
if x <= y
.
If you want a nested loop and you only have two iterables, just use a nested loop:
for i in range(x):
for i in range(y):
…
If you have more than two iterables, use itertools.product
.
Finally, if you want lock-step iteration up to x
and then to continue to y
, you have to decide what the rest of the x
values should be.
for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
…
# or
for i in range(min(x,y)):
j = i
…
for i in range(min(x,y), max(x,y)):
j = float('nan')
…
"Python 3."
Add 2 vars with for loop using zip and range; Returning a list.
Note: Will only run till smallest range ends.
>>>a=[g+h for g,h in zip(range(10), range(10))]
>>>a
>>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
I think you are looking for nested loops.
Example (based on your edit):
t1=[1,2,'Hello',(1,2),999,1.23]
t2=[1,'Hello',(1,2),999]
t3=[]
for it1, e1 in enumerate(t1):
for it2, e2 in enumerate(t2):
if e1==e2:
t3.append((it1,it2,e1))
# t3=[(0, 0, 1), (2, 1, 'Hello'), (3, 2, (1, 2)), (4, 3, 999)]
Which can be reduced to a single comprehension:
[(it1,it2,e1) for it1, e1 in enumerate(t1) for it2, e2 in enumerate(t2) if e1==e2]
But to find the common elements, you can just do:
print set(t1) & set(t2)
# set([(1, 2), 1, 'Hello', 999])
If your list contains non-hashable objects (like other lists, dicts) use a frozen set:
from collections import Iterable
s1=set(frozenset(e1) if isinstance(e1,Iterable) else e1 for e1 in t1)
s2=set(frozenset(e2) if isinstance(e2,Iterable) else e2 for e2 in t2)
print s1 & s2
For your use case, it may be easier to utilize a while
loop.
t1 = [137, 42]
t2 = ["Hello", "world"]
i = 0
j = 0
while i < len(t1) and j < len(t2):
print t1[i], t2[j]
i += 1
j += 1
# 137 Hello
# 42 world
As a caveat, this approach will truncate to the length of your shortest list.
참고URL : https://stackoverflow.com/questions/18648626/for-loop-with-two-variables
'program tip' 카테고리의 다른 글
rails3 프로젝트에서 gem을 제거하는 가장 좋은 방법은 무엇입니까? (0) | 2020.08.20 |
---|---|
Go를 사용하여 대용량 파일을 효율적으로 다운로드하려면 어떻게해야합니까? (0) | 2020.08.20 |
0.1 float는 0.1 double보다 큽니다. (0) | 2020.08.20 |
git log로만 변경된 파일 이름을 표시하는 방법은 무엇입니까? (0) | 2020.08.20 |
HTML 스팬 정렬 센터가 작동하지 않습니까? (0) | 2020.08.20 |