search
HomeBackend DevelopmentPython Tutorialpython开发之for循环操作实例详解

本文实例讲述了python开发之for循环操作。分享给大家供大家参考,具体如下:

下面是我做的一些学习记录供大家参考:

#基本的for循环语句
test_list = [2,"Jone",3,6,7,'hongten','hanyuan','good',"Tom"]
#打印列表的长度
print(len(test_list))
#遍历列表
for i in test_list:
  print(i)
test_str = "hello,i'm hongten"
print('打印字符串:' + test_str)
#遍历一个字符串
print('遍历一个字符串')
for i in test_str:
  print(i)
test_tuple = [("a",1),("b",2),("c",3),("d",4)]
print(test_tuple)
#遍历一个元组
print('遍历一个元组')
for (i,j) in test_tuple:
  print(i,j)
test_dict = {'name':'hongten','age':'20','gender':'M','sports':'足球,乒乓球,游泳'}
#字典迭代器
for key in test_dict:
  print(key + ':' + test_dict[key])
L1 = [1,3,5,7]
L2 = [2,4,6,8]
#使用zip将两个列表合并
print(zip(L1,L2))
for (i,j) in zip(L1,L2):
  print(i,j)
print('#######################################################')
L3 = L2[:]
L3.remove(8)
print('L1,L3列表为:')
print(L1)
print(L3)
for (i,j) in zip(L1,L3):
  print(i,j)
#可以看出来当长度不一的时候,多余的被忽略
test_keys = ['name','age','gender','weight','hight']
test_values = ['Hongten','20','M','55','170']
#使用zip来构造一个字典
print('字典中的keys:')
print(test_keys)
print('字典中的key对应的value:')
print(test_values)
print('构造字典后')
test_dic = dict(zip(test_keys,test_values))
for key in test_dic:
  print( key + ':' + test_dic[key])

运行效果:

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
9
2
Jone
3
6
7
hongten
hanyuan
good
Tom
打印字符串:hello,i'm hongten
遍历一个字符串
h
e
l
l
o
,
i
'
m
 
h
o
n
g
t
e
n
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
遍历一个元组
('a', 1)
('b', 2)
('c', 3)
('d', 4)
gender:M
age:20
name:hongten
sports:足球,乒乓球,游泳
[(1, 2), (3, 4), (5, 6), (7, 8)]
(1, 2)
(3, 4)
(5, 6)
(7, 8)
#######################################################
L1,L3列表为:
[1, 3, 5, 7]
[2, 4, 6]
(1, 2)
(3, 4)
(5, 6)
字典中的keys:
['name', 'age', 'gender', 'weight', 'hight']
字典中的key对应的value:
['Hongten', '20', 'M', '55', '170']
构造字典后
gender:M
age:20
name:Hongten
weight:55
hight:170
>>>

希望本文所述对大家Python程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)