【问题标题】:Print the first three characters of each item in the list which has more than 5 characters打印列表中超过 5 个字符的每个项目的前三个字符
【发布时间】:2020-06-28 18:53:09
【问题描述】:
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

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

【问题讨论】:

  • print('\n'.join(s[:3] for s in items if len(s)>5))
  • 好的,我会试试的:)

标签: python python-3.x string list slice


【解决方案1】:
items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for item in items:
  if len(item) >= 5:
    print(item[:3])

【讨论】:

  • 这里没有理由使用enumerate。你可以使用for item in items 就足够了。
【解决方案2】:

您可以在此处使用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

【讨论】:

    【解决方案3】:

    这应该比你的代码更好。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2016-01-06
      • 2016-10-29
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多