range()를 Python의 목록으로
종종 우리는 100-200 범위의 연속 값을 포함하는 목록을 만들고 싶어합니다. 다음을 사용하여 목록을 만드는 방법에 대해 논의해 보겠습니다. range()> 기능.
이것이 작동할까요?
# Create a list in a range of 10-20> My_list> => [> range> (> 10> ,> 20> ,> 1> )]> > # Print the list> print> (My_list)> |
출력 :
출력에서 볼 수 있듯이 Python은 range() 함수의 결과를 압축 해제하지 않기 때문에 결과는 정확히 우리가 기대했던 것과 다릅니다.
코드 #1: 인수 압축 해제 연산자를 사용할 수 있습니다. * .
# Create a list in a range of 10-20> My_list> => [> *> range> (> 10> ,> 21> ,> 1> )]> > # Print the list> print> (My_list)> |
출력 :
출력에서 볼 수 있듯이 인수 압축 해제 연산자는 범위 함수의 결과를 성공적으로 압축 해제했습니다.
코드 #2: 우리는 extend()> 범위 함수의 결과를 압축 해제하는 함수입니다.
# Create an empty list> My_list> => []> > # Value to begin and end with> start, end> => 10> ,> 20> > # Check if start value is smaller than end value> if> start # unpack the result My_list.extend(range(start, end)) # Append the last value My_list.append(end) # Print the list print(My_list)> |
출력 :