2017-12-02 2 views
2

크레용 제조업체 용 프로그램을 작성 중입니다. 그들은 4 팩의 재고가 있습니다 (지금은 디버깅을위한 좋은 출발점이기 때문에). 나는 목록에 그것을 보여 주었다 :중첩 목록의 특정 목록에서 값 바꾸기

colors=[['pink','green','blue'],['blue','green','red'],['pink',blue','yellow'],['orange','pink','yellow']] 

내가 그린 색상의 더 다양한 팩을 얻을 수있는 중간에 어디 두 팩에 크레용의 색상을 변경하고 싶습니다. 먼저 나는 중간에 녹색 모든 팩을 찾을 :

packsfound = [] 

for pack in colors: 
if pack[1]=="green": 
    packsfound.append(pack) 

print("packs with one:",packsfound) 

그때 나는 주식 (색)에서 선택한 팩을 제거 그래서 그들은 수정하고 나중에 다시 넣을 수 있습니다. 그런 다음

try: 
for pack in packsfound: 
    colors.remove(pack) 
except Exception as e: 
    print(e) 
    pass 

내가 대체 할 : 그들은 재고 새로운 그래서 나는 색상에 다시 수정 된 목록을 추가 그리고

for pack in packsfound: 
try: 
for i, color in enumerate(packsfound): 
    position=color.index("green") 
    print("replace at:",position) 
    break 

pack[position]="yellow" 
print("replaced rows:",packsfound) 
except Exception as e: 
print(e) 
pass 

try: 
for pack in packsfound:   
    colors.append(pack) 
except Exception as e: 
    print(e) 
    pass 

print(colors) 

문제는 단지 통과한다는 것입니다 첫 번째 목록은 첫 번째 녹색을 대체합니다. 나는 제외하고 시도 및 이동과 교체 라인을 이동 및 루프, 추가 브레이크 아웃과 같은 많은 것들을 시도

packs with one: [['pink', 'green', 'blue'], ['blue', 'green', 'red']] 
replace at: 1 
replaced rows: [['pink', 'yellow', 'blue'], ['blue', 'green', 'red']] 
'green' is not in list 
[['pink', 'blue', 'yellow'], ['orange', 'pink', 'yellow'], ['pink', 'yellow', 'blue'], ['blue', 'green', 'red']] 

: 그런 다음 프로그램은 녹색이 목록에없는 두 번째 녹색를 대체하지 않습니다 말한다 통과하지만 아무것도 작동하지 않습니다.

답변

1

대체 루프에 실수가 있습니다. break 문을 두는 방법은 루프의 한 번의 반복 만 허용합니다. 다음 루프를 사용할 수 있습니다.

for pack in packsfound: 
    try: 
     position = pack.index('green') 
     print("replace at:",position) 
     pack[position]="yellow" 
     print("replaced rows:",packsfound) 
except Exception as e: 
     print(e) 
     pass 
0

목록의 요소를 변경하는 대신 새 목록을 작성하고 반환하는 것이 더 쉽습니다. list comprehensionif/else와 간단한 사용 :

>>> mid = int(len(colors[0])/2) 
>>> [ color[:mid]+['yellow']+color[mid+1:] if color[mid]=='green' else color for color in colors ] 
=> [['pink', 'yellow', 'blue'], ['blue', 'yellow', 'red'], ['pink', 'blue', 'yellow'], ['orange', 'pink', 'yellow']] 

참고 영업 이익 : 이것은 당신이 yellowmiddlegreen 만 색상을 교체 할 것을 고려하고있다. 그렇지 않으면 모든 '녹색'요소를 yellow으로 바꿔야합니다. 바꾸기를 사용하십시오. 영업 이익

참고 : 그리고이 한 세트 색상의 홀수의 경우입니다. 그렇지 않으면, 중간의 두 요소가 있으므로 코드를 적절하게 변경하십시오.

0

교체 단계가 문제가 될 것으로 생각됩니다. 중첩 된 목록을 열거 할 때 실수를하는 것처럼 보입니다. 나는 당신이 찾고있는 색상 값의 인덱스를 얻기 위해 이미 .index()을 사용할 때 목록을 열거하려고하는 이유를 확신하지 못합니다.

packsfound = [['pink', 'green', 'blue'], ['blue', 'green', 'red']] 

for pack in packsfound: 
    try: 
    for color in pack: 
     position = pack.index('green') 
     print("replace at: ", position) 
     break 
    pack[position] = 'yellow' 
    print("replaced rows: ", packsfound) 
    except Exception as e: 
    print(e) 
    pass 

변명을 변명 해주십시오. 출력 :

replace at: 1 
replaced rows: [['pink', 'yellow', 'blue'], ['blue', 'green', 'red']] 
replace at: 1 
replaced rows: [['pink', 'yellow', 'blue'], ['blue', 'yellow', 'red']] 
+0

ㅎ ... @Toothless와 같은 응답입니다. 12 초 만에 뛰십시오! xD – musikreck

관련 문제