요소 이름, 날짜 및 추가 데이터가있는 sub_list가 포함 된 목록에서 유사한 요소를 제거하려고합니다.
basket = [['cheese', '2015/04/16', 'junk'],['apple', '2015/04/15', 'other junk'],['apple', '2015/03/15', 'dessert'],['cheese', '2017/04/16', 'pie'],['banana', '2015/04/16', ''],['cheese', '2017/04/10', '']]
요소 이름 (과일)이 목록에 두 번 나타나면 프로그램은 날짜를 비교하고 이전 요소를 제거해야합니다. 두 번째 요소를 비교하기 위해 datetime 을 사용하고 있으며이 부분은 작동합니다. 그러나 목록을 반복하면 계속 건너 뜁니다 'banana'
. 그리고 이것은 추가 할 마지막 항목이어야합니다.
이 방법을 시도했습니다.
def date_convert(date):
"""Takes a date string in the form YYYY/MM/DD and converts it to a
date object for comparisons."""
# Split date string by ".", " ", "/", or "-" to handle a wider range
# of possible inputs.
date = re.split('[. /\-]', date)
# Strip month of "0" because datetime does not accept that as valid
# input.
if(date[1][0] == '0'):
date[1] = date[1].strip('0')
return datetime.date(int(date[0]), int(date[1]), int(date[2]))
basket = [['cheese', '2015/04/16'],['apple', '2015/04/15'],['apple', '2015/03/15'],['cheese', '2017/04/16'],['banana', '2015/04/16'],['cheese', '2017/04/10']]
new_basket = []
for food in basket:
basket.remove(food)
for food2 in basket:
if food[0].upper() == food2[0].upper():
basket.remove(food2)
if date_convert(food[1]) > date_convert(food2[1]):
pass
else:
food = food2
else: new_basket.append(food)
print str(new_basket)
이 인쇄물을 받으십시오. [['cheese', '2017/04/16', 'pie'], ['apple', '2015/04/15', 'other junk']]
디버거에 따르면 for 루프에서 바나나에 도달하지 않습니다.
여기에 한 가지 옵션이 있습니다. 를 사용하여 내부 하위 목록의 첫 번째 항목별로 그룹화 defaultdict
. 날짜 문자열을 실제 날짜와 비교하는 데 도움 max()
이되는 사용자 지정 key
함수로 최대 날짜를 찾는 데 사용 :
from collections import defaultdict
from datetime import datetime
basket = [['cheese', '2015/04/16', 'junk'],['apple', '2015/04/15', 'other junk'],['apple', '2015/03/15', 'dessert'],['cheese', '2017/04/16', 'pie'],['banana', '2015/04/16', ''],['cheese', '2017/04/10', '']]
d = defaultdict(list)
for item in basket:
d[item[0]].append(item[1:])
print([[key, max(values, key=lambda x: datetime.strptime(x[0], "%Y/%m/%d"))] for key, values in d.items()])
인쇄물:
[['apple', ['2015/04/15', 'other junk']], ['banana', ['2015/04/16', '']], ['cheese', ['2017/04/16', 'pie']]]
이 경우 주문이 취소됩니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다