python - 如何访问列表列表中的每个字符串
问题描述
我的任务是输入多行,每行由多个单词组成。任务是将奇数长度的单词大写,偶数长度的单词小写。我的代码现在看起来像这样,你能帮我解决吗?
first = []
while True:
line = input().split()
first.append(line)
if len(line) < 1:
break
for i in first:
for j in i:
if len(line[i][j]) % 2 == 0:
line[i][j] = line[i][j].lower()
elif len(line[i][j]) % 2 != 0:
line[i][j] = line[i][j].upper()
print(first[i])
解决方案
因此,查看图像中的输入输出,这是一个更好的解决方案
sentences = []
while True:
word_list = input().split()
sentences = [*sentences, word_list]
if len(word_list) < 1:
break
所以现在你已经从命令行输入你可以做
[word.upper() if len(word)%2 == 1 else word.lower() for word_list in sentences for word in word_list]
或者你可以提取到一个函数中
def apply_case(word):
if len(word)%2:
return word.upper()
return word.lower()
new_sentences = [apply_case(word) for word_list in sentences for word in word_list]
现在你可以像这样打印它
output = "\n".join([" ".join(word_list) for word_list in new_sentences])
print(output)
推荐阅读
- ios - 在 Swift 中使用队列同步 API 请求?
- c# - 如何在没有属性的情况下记录消息
- python - 计算经常性客户
- python - 如何正确组合 tf.data.Dataset 和 tf.estimator.DNNRegressor
- swagger-ui - SwaggerUI 3.x:如何以编程方式设置参数值?
- javascript - 正则表达式匹配环境
- r - 如何使用apply函数计算两个矩阵之间的距离
- javascript - 传单:使用 CRS.Simple 在 createTile 中获取纬度/经度
- c# - Azure Functions - nodejs 和 dot net core 2.2 内存消耗不断增长,直到回收
- ruby-on-rails - 什么可能导致数据库被意外截断?