请指教 - Python 中的基本 For 循环效率
Advice Please - Basic For Loop Efficiency in Python
首先,我想澄清一下,我目前正在学习Python。所以这可能是一个初学者级别的问题。提前感谢任何 advice/responses.
目前,我正在学习的课程是循环和迭代。我决定自己做一些工作,并为简单的练习提出自己的挑战。
我的个人挑战:
创建一个字符串并将其存储在一个变量中,然后使用枚举器,以相反的顺序输出该字符串。
**我知道还有其他方法可以做到这一点,但是,我有意尝试了解枚举器可以提供多少灵活性。
我经历了几种我知道最有效的格式,但是,我能想到的最好的格式(根据我目前的知识)是这样的:
mystring1 = 'Zero'
for index,letter in enumerate(mystring1):
if index == 0:
index0 = index,letter
print('First Index:',index0,'\n')
index += 1
if index == 1:
index1 = index,letter
print('Second Index:',index1,'\n')
index += 1
if index == 2:
index2 = index,letter
print('Third Index:',index2,'\n')
index += 1
if index == 3:
index3 = index,letter
print('Fourt Index:',index3,'\n')
index += 1
else:
continue
else:
continue
else:
continue
else:
print('All Letters Captured')
break
print(index3, index2, index1, index0)
使用上面的代码,这是我的输出,但是,有两个问题:我没有抓取对应索引的字母,我觉得我完成它的效率不高。
First Index: (0, 'Z')
Second Index: (1, 'Z')
Third Index: (2, 'Z')
Fourt Index: (3, 'Z')
(3, 'Z') (2, 'Z') (1, 'Z') (0, 'Z')
All Letters Captured
我对 C# 有一点了解,我最担心的是得到一个类似于数组的输出;我会有所有可能的组合。
任何提示或建议都会很棒。只是想学习!
再次感谢大家的宝贵时间!
我认为第一个问题是您的代码没有按照您的意愿执行,而不是效率不高。因为每个 if 语句的末尾都有 index += 1
,所以程序实际上在第一个循环中分配了所有索引(这就是为什么与每个索引关联的字母是 Z
)。更简洁的方法可能看起来像
a = []
for index,letter in enumerate(mystring1):
a.insert(0,(index,letter))
a
是一个列表,每次我们调用 a.insert(0,...)
时我们都会在该列表前面添加(有效地反转枚举器)。它输出
[(3, 'o'), (2, 'r'), (1, 'e'), (0, 'Z')]
首先,我想澄清一下,我目前正在学习Python。所以这可能是一个初学者级别的问题。提前感谢任何 advice/responses.
目前,我正在学习的课程是循环和迭代。我决定自己做一些工作,并为简单的练习提出自己的挑战。
我的个人挑战: 创建一个字符串并将其存储在一个变量中,然后使用枚举器,以相反的顺序输出该字符串。
**我知道还有其他方法可以做到这一点,但是,我有意尝试了解枚举器可以提供多少灵活性。
我经历了几种我知道最有效的格式,但是,我能想到的最好的格式(根据我目前的知识)是这样的:
mystring1 = 'Zero'
for index,letter in enumerate(mystring1):
if index == 0:
index0 = index,letter
print('First Index:',index0,'\n')
index += 1
if index == 1:
index1 = index,letter
print('Second Index:',index1,'\n')
index += 1
if index == 2:
index2 = index,letter
print('Third Index:',index2,'\n')
index += 1
if index == 3:
index3 = index,letter
print('Fourt Index:',index3,'\n')
index += 1
else:
continue
else:
continue
else:
continue
else:
print('All Letters Captured')
break
print(index3, index2, index1, index0)
使用上面的代码,这是我的输出,但是,有两个问题:我没有抓取对应索引的字母,我觉得我完成它的效率不高。
First Index: (0, 'Z')
Second Index: (1, 'Z')
Third Index: (2, 'Z')
Fourt Index: (3, 'Z')
(3, 'Z') (2, 'Z') (1, 'Z') (0, 'Z')
All Letters Captured
我对 C# 有一点了解,我最担心的是得到一个类似于数组的输出;我会有所有可能的组合。
任何提示或建议都会很棒。只是想学习!
再次感谢大家的宝贵时间!
我认为第一个问题是您的代码没有按照您的意愿执行,而不是效率不高。因为每个 if 语句的末尾都有 index += 1
,所以程序实际上在第一个循环中分配了所有索引(这就是为什么与每个索引关联的字母是 Z
)。更简洁的方法可能看起来像
a = []
for index,letter in enumerate(mystring1):
a.insert(0,(index,letter))
a
是一个列表,每次我们调用 a.insert(0,...)
时我们都会在该列表前面添加(有效地反转枚举器)。它输出
[(3, 'o'), (2, 'r'), (1, 'e'), (0, 'Z')]