在理解范围内访问字符串的索引
Accessing index of a string within a comprehension
>> names = ["Cola", "Salah"]
>> names1 = [s for s in names for i,c in enumerate(s)]
Output: "Cola","Cola","Cola","Cola","Salah","Salah","Salah","Salah","Salah",
我正在尝试使用 python 理解,而不是输出 Cola 和 Salah 5 次,输出将是:
output: "Coolllaaaa", "Saalllaaaahhhhh"
我想知道我们如何访问字符串的索引。
该代码应该能够接受 unicode。
这是一种使用 enumerate
遍历字符串元素中的每个索引和字符的方法:
>>> names = ["Cola", "Salah"]
>>> [''.join([c * i for i, c in enumerate(s, 1)]) for s in names]
['Coolllaaaa', 'Saalllaaaahhhhh']
这使用了两个 list
理解,第一个遍历 names
中的每个字符串,第二个遍历字符串中的每个字符和索引,然后将这些值相乘并将它们连接成一个新字符串。
>> names = ["Cola", "Salah"]
>> names1 = [s for s in names for i,c in enumerate(s)]
Output: "Cola","Cola","Cola","Cola","Salah","Salah","Salah","Salah","Salah",
我正在尝试使用 python 理解,而不是输出 Cola 和 Salah 5 次,输出将是:
output: "Coolllaaaa", "Saalllaaaahhhhh"
我想知道我们如何访问字符串的索引。 该代码应该能够接受 unicode。
这是一种使用 enumerate
遍历字符串元素中的每个索引和字符的方法:
>>> names = ["Cola", "Salah"]
>>> [''.join([c * i for i, c in enumerate(s, 1)]) for s in names]
['Coolllaaaa', 'Saalllaaaahhhhh']
这使用了两个 list
理解,第一个遍历 names
中的每个字符串,第二个遍历字符串中的每个字符和索引,然后将这些值相乘并将它们连接成一个新字符串。