繁体   English   中英

打印列表中每项超过 5 个字符的前三个字符

[英]Print the first three characters of each item in the list which has more than 5 characters

items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for word in items:
   print(word[:3])
#prints the first three characters of each item

def string_k(k, str):
  string = []
  text = str.split(" ")
  for x in text:
    if len(x) > k:
      string.append(x)
  return string
k = 6
str = "Apple, Banana, Cherry, Date, Eggfruit, Fig"
print(string_k(k, str))
#This prints out every item in the list that has more than five characters

这类似于我的第一个问题 - 我有两个单独的代码,但我不明白如何将它们组合在一起以获得我需要的输出

您可以在此处使用filter

items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]

for _str in filter(lambda x:len(x)>=5,items):
    print(_str[:3])

输出:

App
Ban
Che
Egg

这应该比您的代码更有效。

items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for i in range(0, len(items)):
    if len(i) >= 5:
        print(i[:3])
items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for item in items:
  if len(item) >= 5:
    print(item[:3])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM