Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

튜플 목록의 요소를 부동 소수점으로 변환하는 Python 프로그램

<시간/>

튜플 목록의 요소를 float 값으로 변환해야 하는 경우 'isalpha' 방법, 'float' 방법 및 단순 반복이 사용됩니다.

아래는 동일한 데모입니다 -

예시

my_list = [("31", "py"), ("22", "226.65"), ("18.12", "17"), ("pyt", "12")]

print("The list is :")
print(my_list)

my_result = []
for index in my_list:
   my_temp = []
   for element in index:

      if element.isalpha():
         my_temp.append(element)
      else:

         my_temp.append(float(element))
   my_result.append((my_temp[0],my_temp[1]))

print("The result is :")
print(my_result)

출력

The list is :
[('31', 'py'), ('22', '226.65'), ('18.12', '17'), ('pyt', '12')]
The result is :
[(31.0, 'py'), (22.0, 226.65), (18.12, 17.0), ('pyt', 12.0)]

설명

  • 정수 목록이 정의되어 콘솔에 표시됩니다.

  • 빈 목록이 선언되었습니다.

  • 목록이 반복되고 isalpha() 함수를 사용하여 요소에 알파벳이 있는지 확인합니다.

  • 조건이 충족되면 요소를 그대로 추가하고, 조건이 충족되지 않으면 요소를 float로 변환하여 추가합니다.

  • 이 결과는 변수에 할당됩니다.

  • 콘솔에 표시되는 출력입니다.