반환된 목록에서 장소가 바뀐 항목 삭제 (Deleting items that have the place swapped around in a returned list)


문제 설명

반환된 목록에서 장소가 바뀐 항목 삭제 (Deleting items that have the place swapped around in a returned list)

내 함수는 숫자와 숫자 목록을 사용합니다.

목록에 있는 2개의 숫자가 원래 숫자에 더해진다면 [Num1, Num2] 형식입니다. .

이제 "중복"을 원하지 않습니다. 즉, [4, ‑7]만 반환되고 [4, ‑7], [‑ 7, 4].

def pairs(n, num_list):
    newest_list = []
    for j in range(len(num_list)):
        for i in range(len(num_list)‑1):
            if num_list[j] + num_list[i+1] == n:
                newest_list.append([num_list[j], num_list[i+1]])
    return newest_list

이제 코드를 게시하는 것보다 간단한 힌트를 원합니다. 제 질문은 다음과 같습니다.

내 코드 내에서 그렇게 할 수 있는 능력이 있습니까? 그렇다면 힌트가 좋을 것입니다. 아니면 그렇게 하기 위해 다른 함수를 정의해야 합니까?


참조 솔루션

방법 1:

You definitely have the ability to do that within your code.

A hint to complete this would be to think about at what point in your code it makes sense to stop searching for further matches and to return what you've found. Let me know if that's too cryptic!

방법 2:

You can still do that in your current code by simply appending these two numbers into a Set. For more info, this will help you.

방법 3:

When adding a pair [a, b] to the result list, sort the pair, then see if it's in the result list. If so, don't add it.

Also, consider using a Python set.

방법 4:

if you have 2 lists l1, and l2 where:

l1=[1,2]
l2=[2,1]

If you convert them to sets, you can compare them and they will evaluate to True if they have the same elements, no matter what the order is:

set(l1) == set(l2) # this evaluates to True

In your if condition, before appending the numbers, you can check if the set set([num_list[j], num_list[i+1]]) is already in newest_list.

I am tempted to write some code, but you said not to, so I'll leave it here :p

방법 5:

You can leave your code the way it is, but before you return the list, you can filter the list with a predicate that the pair [a,b] is only accepted if pair [b,a] is not in the list

(by RonaldBQichao ZhaoeshirimajohntellsallJesusAlvSotosmac89)

참조 문서

  1. Deleting items that have the place swapped around in a returned list (CC BY‑SA 2.5/3.0/4.0)

#list #Python






관련 질문

파이썬에서 데이터를 정렬하는 방법 (How arrange data in python)

포스트백 후 모든 항목이 손실되는 CheckBoxList 컨트롤 (CheckBoxList control losing all items after post back)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

DictReader가 내 파일의 두 줄을 건너뛰고 있습니까? (DictReader is skipping two lines of my file?)

잘못된 값을 얻는 목록 확인 후 (After list checking getting wrong value)

결과를 세로 방향으로 저장하는 방법 (How do i save the result in a Vertical direction)

Python 2.x: 튜플 목록의 항목 합계 (Python 2.x: Summing items in a list of tuples)

itemgetter를 사용하지 않고 n번 발생하는 요소가 있는 목록 내 항목 인쇄 (Printing items inside a list which have an element that occurs n times without using itemgetter)

반환된 목록에서 장소가 바뀐 항목 삭제 (Deleting items that have the place swapped around in a returned list)

arrayToList가 홀수 출력을 생성합니다. 뭐가 문제 야? (arrayToList producing odd outputs. What's wrong?)

R 목록을 벡터로 바꾸는 방법과 목록이 필요한 이유 (R how to turn lists to vectors, and why a list at all)

python, 출력으로 코딩하는 동안 pycharm에서 이 메시지를 받았습니다. :TypeError: can't convert type 'list' to numerator/denominator (python , I got this message in pycharm while coding as output :TypeError: can't convert type 'list' to numerator/denominator)







코멘트