인덱싱과 슬라이싱을 배운 후 목록과 내장 메서드에 대해 더 많이 배우기 시작했습니다. 방법은
반환 없음
- 추가
- 삽입
- 제거
- 정렬
- 역방향
- 맑음
정수 반환
- 색인
- 개수
str을 반환합니다
- 팝
배송 목록의 작은 변경 사항은 내장된 기능 자체만으로도 충분합니다. 그러나 목록으로 더 많은 작업을 수행하려면 for 루프, if 루프가 필요합니다.
예를 들어 문자열만 변환해야 하는 목록 ['연필', '노트북', '마커', '형광펜', '접착제', '지우개', '노트북', 3]이 있습니다. 대문자. 여기서는 목록이나 문자열 메서드를 직접 사용할 수 없습니다. 이상적인 논리는
- 목록을 하나씩 반복해야 합니다
- 항목이 문자열인지 다른 유형인지 확인
- 문자열 메서드 upper() 및 Append()를 적절하게 사용하세요
여기서 for 루프, if,else 조건이 필요합니다
delivery_list= ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop', 3] upper_list = [] for item in delivery_list: if type(item) == str: upper_list.append(item.upper()) else: upper_list.append(item) print('Upper case list is:', upper_list) Output: Upper case list is: ['PENCIL', 'NOTEBOOK', 'MARKER', 'HIGHLIGHTER', 'GLUE STICK', 'ERASER', 'LAPTOP', 3]
그러한 방법과 논리를 좀 더 연습하라는 과제가 주어졌습니다. 사용 가능한 논리나 방법을 찾는 것이 흥미로웠습니다.
해결내역은
Tasks_list.py ####################################################################################### #1. Create a list of five delivery items and print the third item in the list. #eg: [“Notebook”, “Pencil”, “Eraser”, “Ruler”, “Marker”] ####################################################################################### delivery_list = ['Notebook', 'Pencil', 'Eraser', 'Ruler', 'Marker'] print (f'\t1. Third item in the list{delivery_list} is: {delivery_list[2]}') ####################################################################################### # 2.A new delivery item “Glue Stick” needs to be added to the list. # Add it to the end of the list and print the updated list. ####################################################################################### delivery_list.append('Glue Stick') print('\t2. Updated delivery list is:', delivery_list) ####################################################################################### # 3. Insert “Highlighter” between the second and third items and print the updated list. ####################################################################################### delivery_list.insert(2, 'Highlighter') print('\t3. Updated list by inserting Highlighter b/w 2nd &3rd:', delivery_list) ####################################################################################### # 4. One delivery was canceled. Remove “Ruler” from the list and print the updated list. ####################################################################################### delivery_list.remove('Ruler') print('\t4. Updated list after removing Ruler is:', delivery_list) ####################################################################################### # 5. The delivery man needs to deliver only the first three items. # Print a sublist containing only these items. ####################################################################################### sublist =[] for item in delivery_list[:3]: #sublist =sublist.append(item) #This is incorrect as sublist.append() returns None. sublist.append(item) print('\t5. Sublist of first three elements using loop:', sublist) print('\t Sublist of first three elements using slicing:', delivery_list[:3]) ####################################################################################### # 6.The delivery man has finished his deliveries. # Convert all item names to uppercase using a list comprehension and print the new list. ####################################################################################### uppercase_list=[] for item in delivery_list: uppercase_list.append(item.upper()) print('\t6. Uppercase list of delivery items:', uppercase_list) uppercase_list_lc = [item.upper() for item in delivery_list] print('\t6. Uppercase list using list compre:', uppercase_list_lc) ####################################################################################### # 7. Check if “Marker” is still in the list and print a message indicating whether it is found. # 8. Print the number of delivery items in the list. ####################################################################################### is_found= delivery_list.count('Marker') if 'Marker' in delivery_list: print(f'\t7. Marker is found {is_found} times') else: print(f'\t7. Marker is not found {is_found}') print(f'\t8. Number of delivery item from {delivery_list} is: ', len(delivery_list)) ####################################################################################### # 9. Sort the list of items in alphabetical order and print the sorted list # 10. The delivery man decides to reverse the order of his deliveries. # Reverse the list and print it ####################################################################################### delivery_list.sort() print(f'\t9. Sorted delivery list is {delivery_list}') delivery_list.reverse() print(f'\t10. Reverse list of delivery list is {delivery_list}') ####################################################################################### # 11. Create a list where each item is a list containing a delivery item and its delivery time. # Print the first item and its time. ####################################################################################### delivery_list_time = [['Letter', '10:00'], ['Parcel', '10:15'], ['Magazine', '10:45'], ['Newspaper', '11:00']] print('\t11. First delivery item and time', delivery_list_time[0]) delivery_list = ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop'] delivery_time = ['11:00','11:20','11:40','12:00','12:30','13:00', '13:30'] #Paring of two list using zip paired_list=list(zip(delivery_list,delivery_time)) print('\tPaired list using zip:', paired_list[0:2]) #Combine corresponding item from multiple list using zip and for item_time_list = [[item,time] for item, time in zip(delivery_list, delivery_time)] print ('\tItem_time_list using list comprehension: ', item_time_list[0:1]) ####################################################################################### # 12. Count how many times “Ruler” appears in the list and print the count. # 13. Find the index of “Pencil” in the list and print it. # 14. Extend the list items with another list of new delivery items and print the updated list. # 15. Clear the list of all delivery items and print the list. # 16. Create a list with the item “Notebook” repeated three times and print the list. # 17. Using a nested list comprehension, create a list of lists where each sublist contains an item # and its length, then print the new list. # 18. Filter the list to include only items that contain the letter “e” and print the filtered list. # 19. Remove duplicate items from the list and print the list of unique items. ####################################################################################### is_found= delivery_list.count('Ruler') print('\t12. The count of Ruler in delivery list is:', is_found) index_pencil = delivery_list.index('Pencil') print(f'\t13. Index of Pencil in {delivery_list} is {index_pencil}') small_list = ['Ink',''] delivery_list.extend(small_list) print('\t14. Extend list by extend:', delivery_list) item_time_list.clear() print('\t15. Clearing the list using clear():', item_time_list) Notebook_list = ['Notebook']*3 print('\t16. Notebook list is:', Notebook_list) #Filter the list with e letter delivery_list new_delivery_list = [] for item in delivery_list: if 'e' in item: new_delivery_list.append(item) print ('\t18. Filtered list with items containing e:', new_delivery_list) new_list_compre = [item for item in delivery_list if 'e' in item] print ('\t18. Filtered list by list comprehension:', new_list_compre) #Remove duplicate items delivery_list.extend(['Ink', 'Marker']) print('\t ', delivery_list) for item in delivery_list: if delivery_list.count(item) > 1: delivery_list.remove(item) print('\t19. Duplicate remove list:',delivery_list) print('\t19. Duplicate remove list:',list(set(delivery_list))) ####################################################################################### # 17. Using a nested list comprehension, create a list of lists where each sublist contains an item # and its length, then print the new list. ####################################################################################### #without list comprehension nested_list = [] for item in delivery_list: nested_list.append([item, len(item)]) print('\t17. ', nested_list[-1:-6:-1]) #Using list comprehension printing nested list nested_list = [[item,len(item)] for item in delivery_list] print('\t17. Nested list with length:', nested_list[:5])
정답:
PS C:\Projects\PythonSuresh> python Tasks_list.py 1. Third item in the list['Notebook', 'Pencil', 'Eraser', 'Ruler', 'Marker'] is: Eraser 2. Updated delivery list is: ['Notebook', 'Pencil', 'Eraser', 'Ruler', 'Marker', 'Glue Stick'] 3. Updated list by inserting Highlighter b/w 2nd &3rd: ['Notebook', 'Pencil', 'Highlighter', 'Eraser', 'Ruler', 'Marker', 'Glue Stick'] 4. Updated list after removing Ruler is: ['Notebook', 'Pencil', 'Highlighter', 'Eraser', 'Marker', 'Glue Stick'] 5. Sublist of first three elements using loop: ['Notebook', 'Pencil', 'Highlighter'] Sublist of first three elements using slicing: ['Notebook', 'Pencil', 'Highlighter'] 6. Uppercase list of delivery items: ['NOTEBOOK', 'PENCIL', 'HIGHLIGHTER', 'ERASER', 'MARKER', 'GLUE STICK'] 6. Uppercase list using list compre: ['NOTEBOOK', 'PENCIL', 'HIGHLIGHTER', 'ERASER', 'MARKER', 'GLUE STICK'] 7. Marker is found 1 times 8. Number of delivery item from ['Notebook', 'Pencil', 'Highlighter', 'Eraser', 'Marker', 'Glue Stick'] is: 6 9. Sorted delivery list is ['Eraser', 'Glue Stick', 'Highlighter', 'Marker', 'Notebook', 'Pencil'] 10. Reverse list of delivery list is ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser'] 11. First delivery item and time ['Letter', '10:00'] Paired list using zip: [('Pencil', '11:00'), ('Notebook', '11:20')] Item_time_list using list comprehension: [['Pencil', '11:00']] 12. The count of Ruler in delivery list is: 0 13. Index of Pencil in ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop'] is 0 14. Extend list by extend: ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop', 'Ink', ''] 15. Clearing the list using clear(): [] 16. Notebook list is: ['Notebook', 'Notebook', 'Notebook'] 18. Filtered list with items containing e: ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser'] 18. Filtered list by list comprehension: ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser'] ['Pencil', 'Notebook', 'Marker', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop', 'Ink', '', 'Ink', 'Marker'] 19. Duplicate remove list: ['Pencil', 'Notebook', 'Highlighter', 'Glue Stick', 'Eraser', 'Laptop', '', 'Ink', 'Marker'] 19. Duplicate remove list: ['', 'Ink', 'Pencil', 'Notebook', 'Marker', 'Eraser', 'Laptop', 'Highlighter', 'Glue Stick'] 17. [['Marker', 6], ['Ink', 3], ['', 0], ['Laptop', 6], ['Eraser', 6]] 17. Nested list with length: [['Pencil', 6], ['Notebook', 8], ['Highlighter', 11], ['Glue Stick', 10], ['Eraser', 6]]
위 내용은 Python - 목록 및 작업의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

Python과 C는 메모리 관리 및 제어에 상당한 차이가 있습니다. 1. Python은 참조 계산 및 쓰레기 수집을 기반으로 자동 메모리 관리를 사용하여 프로그래머의 작업을 단순화합니다. 2.C는 메모리 수동 관리가 필요하므로 더 많은 제어를 제공하지만 복잡성과 오류 위험을 증가시킵니다. 선택할 언어는 프로젝트 요구 사항 및 팀 기술 스택을 기반으로해야합니다.

과학 컴퓨팅에서 Python의 응용 프로그램에는 데이터 분석, 머신 러닝, 수치 시뮬레이션 및 시각화가 포함됩니다. 1.numpy는 효율적인 다차원 배열 및 수학적 함수를 제공합니다. 2. Scipy는 Numpy 기능을 확장하고 최적화 및 선형 대수 도구를 제공합니다. 3. 팬더는 데이터 처리 및 분석에 사용됩니다. 4. matplotlib는 다양한 그래프와 시각적 결과를 생성하는 데 사용됩니다.

Python 또는 C를 선택할 것인지 프로젝트 요구 사항에 따라 다릅니다. 1) Python은 간결한 구문 및 풍부한 라이브러리로 인해 빠른 개발, 데이터 과학 및 스크립팅에 적합합니다. 2) C는 컴파일 및 수동 메모리 관리로 인해 시스템 프로그래밍 및 게임 개발과 같은 고성능 및 기본 제어가 필요한 시나리오에 적합합니다.

Python은 데이터 과학 및 기계 학습에 널리 사용되며 주로 단순성과 강력한 라이브러리 생태계에 의존합니다. 1) 팬더는 데이터 처리 및 분석에 사용되며, 2) Numpy는 효율적인 수치 계산을 제공하며 3) Scikit-Learn은 기계 학습 모델 구성 및 최적화에 사용되며 이러한 라이브러리는 Python을 데이터 과학 및 기계 학습에 이상적인 도구로 만듭니다.

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

웹 개발에서 Python의 주요 응용 프로그램에는 Django 및 Flask 프레임 워크 사용, API 개발, 데이터 분석 및 시각화, 머신 러닝 및 AI 및 성능 최적화가 포함됩니다. 1. Django 및 Flask 프레임 워크 : Django는 복잡한 응용 분야의 빠른 개발에 적합하며 플라스크는 소형 또는 고도로 맞춤형 프로젝트에 적합합니다. 2. API 개발 : Flask 또는 DjangorestFramework를 사용하여 RESTFULAPI를 구축하십시오. 3. 데이터 분석 및 시각화 : Python을 사용하여 데이터를 처리하고 웹 인터페이스를 통해 표시합니다. 4. 머신 러닝 및 AI : 파이썬은 지능형 웹 애플리케이션을 구축하는 데 사용됩니다. 5. 성능 최적화 : 비동기 프로그래밍, 캐싱 및 코드를 통해 최적화

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Dreamweaver Mac版
시각적 웹 개발 도구

WebStorm Mac 버전
유용한 JavaScript 개발 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
