【问题标题】:Ways to include list index in string in Python [duplicate]在 Python 中在字符串中包含列表索引的方法 [重复]
【发布时间】:2018-09-14 19:43:13
【问题描述】:

有没有更简单的方法(没有 for 循环)将列表索引包含在一个联合字符串中?
我当前的代码是:

sep = ' - '
a = 'apple - banana - lemon - melon'
b = a.split(sep)
c = ''

for item in b:
    c += str(b.index(item)+1)+'.'+item+sep

d = c[:len(c)-len(sep)]
print(d)

【问题讨论】:

  • 您想要字符串中的索引,还是 [(index, substring), ...] 的子集?
  • 这可以更简洁地表达为sep.join('{}.{}'.format(i, x) for i, x in enumerate(b, start=1))
  • 谢谢帕特里克,这就是我要找的。前两行之后,可以浓缩成一行:d = sep.join('{}.{}'.format(i, s) for i,s in enumerate(a.split(sep), start=1))

标签: python string list indexing


【解决方案1】:

如果您试图避开 for 循环,我认为您正在寻找以下内容:

欲了解更多信息,请查看:enumeratejoin

sep = ' - '
a = 'apple - banana - lemon - melon'
b = a.split(sep) #Turns the string into a list of “items

b = enumerate(b) #Turns the items list into [(item_index, item), ...]
c = f"{b[1]}.{b[0]}" #Formats item.index how you were
d = sep.join(c) #puts them all together in a neat little string separated by “sep”

e = d[:len(d)-len(sep)]
print(e)

不过这一步要简单的分解一下。下面是bcd 分成两行。

sep = ' - '
a = 'apple - banana - lemon - melon'

b = enumerate(a.split(sep))
c = sep.join(f"{b[1]}.{b[0]}")

d = c[:len(c)-len(sep)]
print(d)

不过,如果我没记错的话,list comprehension 仍然会更快。至少对于地图而言。

编辑: 归功于@Patrick Haugh。对于列表理解。

d = sep.join('{}.{}'.format(i, s) for i,s in enumerate(a.split(sep), start=1)

我还根据你的修复了我的,因为我的加入了 str 和 int,我的想法是他试图不使用 for 循环。

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    相关资源
    最近更新 更多