python - 如何制作一个替换特定索引的函数
问题描述
我不认为我已经完全掌握了函数的概念,所以它抑制了我进一步发展自己的能力。我有这个我无法弄清楚的挑战,就在这里。我不清楚如何设置一个函数来做我想要它做的事情,因为括号中的参数让我失望。如果您能告诉我方法而不是修复代码,我会更喜欢它。非常感谢您花时间阅读和/或回复。
Function Challenge: create replacement function¶
Create a function, str_replace, that takes 2 arguments: int_list and index
int_list is a list of single digit integers
index is the index that will be checked - such as with int_list[index]
Function replicates purpose of task "replace items in a list" above and replaces an integer with a string "small" or "large"
return int_list
int_list = [3, 6, 9]
index = int_list[0]
def str_replace(int_list, index=""):
if int_list[0] < 5:
index = 'small'
else:
index = 'large'
print(index)
return str_replace(int_list)
解决方案
这解决了我的问题。
int_list = [1,2,3,4,5] # list created def str_replace(int_list, index): # index is a static position you will type in.
if int_list[index] < 5:
int_list[index] = "small"
else:
int_list[index] = "large"
print "Your index is: ", index
print int_list[:]
str_replace(int_list,1)
推荐阅读
- react-native - React Native 没有连接到 socket.io
- django - GeoDjango 获取到给定位置集的任何点的给定距离内的模型的所有记录
- regex - 如何重复正则表达式组直到字符串结束
- wpf - 为什么带有一个按钮的 WPF CommandBinding 会影响另一个按钮?
- sql - 如何在 CLOB 中搜索字符串并在 Oracle SQL 中显示其后的值?
- here-api - 示例邮政编码的 Here API 的空结果
- python - Python:如何在另一个函数中包含一个函数?
- java - 如何使用 Zxing 更好地读取数据矩阵?
- reactjs - 未处理的拒绝(错误):帖子不能为空
- google-bigquery - Union All 的列数不匹配