파이썬 for문 관련한 질문입니다.
조회수 804회
def ndiv(l,n):
return [l[i:i + n] for i in xrange(0, len(l) // n * n, n)] + [[e] for e in l[len(l) // n * n:]]
print "INSERTION : {}".format(ndiv(insertion, i))
print "INSERTION1 : {}".format(ndiv(insertion1, i))
ds = [sum(sd) for sd in ndiv(insertion,i)]
sa = [sum(aa) for aa in ndiv(insertion1,i)]
ss = [x+y for x,y in zip(ds,sa)]
for ada in ss:
log2 = math.log(float(i + 1), 2)
qq = 3 * ada * (log2)
print "Each Insertion : {}".format(qq)
print "JOINING : {}".format(ndiv(joining, i))
print "JOINING1 : {}".format(ndiv(joining1, i))
aa = [sum(ad) for ad in ndiv(joining,i)]
bb = [sum(ac) for ac in ndiv(joining1,i)]
cc = [x+y for x,y in zip(aa,bb)]
for qwe in cc:
log2 = math.log(float(i + 1), 2)
ab = 4 * qwe * (log2)
print "Each Insertion : {}".format(ab)
안녕하세요, for문을 통해 계산된 결과 값을 따로 빼내어 (각 for문 결과 값) 더하고 싶은데 어떻게 해야할지 잘 몰라 질문 드립니다.
ex) compute = qq + ab
-
(•́ ✖ •̀)
알 수 없는 사용자
2 답변
-
로직이 같으므로 별도의 함수로 분리하세요
# ss, cc 리스트의 필드 값을 모두 더해 반환 def sumOfList(v_list, multiply): result = [] for item in v_list: log2 = math.log(float(i + 1), 2) qq = multiply * item * (log2) print "Each Insertion : {}".format(qq) result.append(qq) return sum(result) def ndiv(l,n): return [l[i:i + n] for i in xrange(0, len(l) // n * n, n)] + [[e] for e in l[len(l) // n * n:]] print "INSERTION : {}".format(ndiv(insertion, i)) print "INSERTION1 : {}".format(ndiv(insertion1, i)) ds = [sum(sd) for sd in ndiv(insertion,i)] sa = [sum(aa) for aa in ndiv(insertion1,i)] ss = [x+y for x,y in zip(ds,sa)] # 함수 이용하여 합계 받음 sumOfSs = sumOfList(ss, 3) print "JOINING : {}".format(ndiv(joining, i)) print "JOINING1 : {}".format(ndiv(joining1, i)) aa = [sum(ad) for ad in ndiv(joining,i)] bb = [sum(ac) for ac in ndiv(joining1,i)] cc = [x+y for x,y in zip(aa,bb)] # 함수 이용하여 합계 받음 sumOfCc = sumOfList(cc, 4) # 두개의 결과를 더함 compute = sumOfSs + sumOfCc
-
흠... 일단 코드 오류는 둘째 치고
원하시는 결과만 알려드리면
for 문이 선언된 동일 indent block에서 할당 하시면 됩니다.
for ada in ss: # ... # qq = 3 * ada * (log2) <= qq 선언 및 값 할당 됨 # ... for qwe in cc: # ... # ab = 4 * qwe * (log2) <= ab 선언 및 값 할당 됨 # ... compute = qq + ab
혹시 이 문제가 아니고 로직의 문제라던가 에러가 나는 상황이면 그 현상을 알려주시고 코드를 다시 정리해서 올려주세요.
댓글 입력