Elementwise multiplication of characters in a list by numbers from a given shorter range while ignoring spaces and digits and joining result together

huangapple go评论89阅读模式
英文:

Elementwise multiplication of characters in a list by numbers from a given shorter range while ignoring spaces and digits and joining result together

问题

我想根据给定的起始和结束范围来对单词的每个字母进行乘法运算。我的当前代码如下,但它不能按预期工作:

word = ['h', 'e', 'l', 'p', 'm', 'e']
start = 3
end = 5
for b in range(start, end + 1):
    for a in word:
        print(a * b, end='')

我的输出是:

hhheeelllpppmmmeeehhhheeeellllppppmmmmeeeehhhhheeeeelllllpppppmmmmmeeeee

但我想要得到:

hhheeeelllllpppmmmmeeeee

这个程序的流程应该像这样:

helpme
345345

另外,如何在列表中忽略空格和数字?例如,我的输入将是:

['h', 'e', 'l', 'p', ' ', 'm', 'e']
start = 3
end = 5

我的输出应该是:

hhheeeelllllppp mmmmeeeee

因此,乘法运算应该是:

help me
3453145
英文:

I want to multiply every letter of a word based on the starting and ending range given. My current code is as follows, but it doesn't work as intended:

word = ['h', 'e', 'l', 'p', 'm', 'e']
start = 3
end = 5
for b in range(start, end + 1):
    for a in word:
        print(a * b, end='')

My output is:

hhheeelllpppmmmeeehhhheeeellllppppmmmmeeeehhhhheeeeelllllpppppmmmmmeeeee

But I want to receive:

hhheeeelllllpppmmmmeeeee

The flow of this program should be like this:

helpme
345345

In addition, how could I ignore spaces and digits in the list? For example, my input would be:

['h', 'e', 'l', 'p', ' ', 'm', 'e']
start = 3
end = 5

And my output:

hhheeeelllllppp mmmmeeeee

so the multiplications should be:

help me
3453145

答案1

得分: 4

以下是您要翻译的内容:

您可以尝试以下方法使用 `zip` 和 [`itertools.cycle`][1]

import itertools

word = ['h', 'e', 'l', 'p', 'm', 'e']
start = 3
end = 5

for a, b in zip(itertools.cycle(range(start, end + 1)), word):
    print(b * a, end='')

**输出结果:**

hhheeeelllllpppmmmmeeeee

或者您可以使用取余运算符和 `enumerate` 来实现

word = ['h', 'e', 'l', 'p', 'm', 'e']
start = 3
end = 5

lst = list(range(start, end + 1))

for i, a in enumerate(word):
    print(a * lst[i % len(lst)], end='')

**要忽略某些字符:**

import itertools

word = ['h', 'e', 'l', 'p', ' ', '1', 'm', 'e']
start = 3
end = 5

characters_to_ignore = ' 0123456789'

gen = itertools.cycle(range(start, end + 1))

lst = [(x, next(gen)) if x not in characters_to_ignore else (x, 1) for x in word]

for a, b in lst:
    print(a * b, end='')

输出结果:

hhheeeelllllppp 1mmmmeeeee
英文:

You could do something like the following, using zip and itertools.cycle:

import itertools

word = ['h', 'e', 'l', 'p', 'm', 'e']
start = 3
end = 5

for a, b in zip(itertools.cycle(range(start, end + 1)), word):
    print(b*a, end = '')

Output:

hhheeeelllllpppmmmmeeeee

Alternatively, you could do this using a modulo operator and enumerate:

word = ['h', 'e', 'l', 'p', 'm', 'e']
start = 3
end = 5

lst = list(range(start, end + 1))

for i, a in enumerate(word):
    print(a*lst[i%len(lst)], end='')

To ignore certain characters:

import itertools

word = ['h', 'e', 'l', 'p', ' ', '1', 'm', 'e']
start = 3
end = 5

characters_to_ignore=' 0123456789'

gen = itertools.cycle(range(start, end + 1))

lst = [(x, next(gen)) if x not in characters_to_ignore else (x, 1) for x in word]

for a, b in lst:
    print(a*b, end='')

Output:

hhheeeelllllppp 1mmmmeeeee

答案2

得分: 3

使用列表推导和join方法:

word = "helpme"
start = 3
end = 5

r = list(range(start, end + 1))

print(''.join([l * r[i % len(r)] for i, l in enumerate(word)]))

输出

hhheeeelllllpppmmmmeeeee
英文:

Using list comprehension and join:

word = "helpme"
start = 3
end = 5

r = list(range(start, end + 1))

print(''.join([l * r[i % len(r)] for i, l in enumerate(word)]))

Output

hhheeeelllllpppmmmmeeeee

答案3

得分: 3

已经提供了很好的答案。我只想补充一下我的答案,这是一行代码(只是为了变化一下)。理想情况下,你应该使用可读性好且代码分隔清晰的方式,但正如我所说,这个解决方案只是为了展示存在的“pythonic多样性”。

word = ['h', 'e', 'l', 'p', 'm', 'e']
print("".join(list(map(lambda a: a[0] * a[1], zip(word, list(range(3, 6)) * (len(word) // 3))))))

输出如下:

hhheeeelllllpppmmmmeeeee

稍后添加的行

在看到有带空格的单词列表的请求后进行编辑

@Faded,我无法想出一个不会损坏基本的健全性检查的“单行”解决方案。一切都有限制,我已经达到了为你所描述的问题制定“一行”解决方案的极限。可能只有我一个人,也许有人可以使用单行Python表达式轻松解决这个问题。我们应该等待那位特殊的火炬传递者。

与此同时,使用多行程序可以很容易地实现相同的效果。其中一种可能的解决方案如下:

word = ['h', 'e', 'l', 'p', '', 'm', 'e']
FinalList = []
MultiplierCount = 3
for i in word:
    if len(i) != 0:
        FinalList.append(i * MultiplierCount)
        MultiplierCount += 1
        if MultiplierCount > 5:
            MultiplierCount = 3
    else:
        FinalList.append(' ')

FinalOutput = "".join(FinalList)
print(FinalOutput)

它会产生以下输出:

hhheeeelllllppp mmmmeeeee
英文:

Already good answers have been given. Just want to add mine which is one liner (just for a change). You should ideally use a well readable and separated code but as I said, this solution is to just bring out 'pythonic variety' that exists :-).

word = ['h', 'e', 'l', 'p', 'm', 'e']
print("".join(list(map(lambda a: a[0]*a[1], zip(word,list(range(3,6))*(len(word)//3))))))

Output is as below

hhheeeelllllpppmmmmeeeee

Lines added later

Edited after seeing a request of word list with space embedded in it

@Faded I can't think of a 'single line' solution without destroying sanity checks beyond repair. Everything has limits and I have hit the limit for producing 'one line' solution for the problem you have described. It could only be me and somebody might have very easy solution using single line python expression. We should wait for that special torch-bearer.

In the meanwhile, it is very easy to achieve the same with a multiline program. One out of many possible solution is as below.

word = ['h', 'e', 'l', 'p', '','m', 'e']
FinalList = []
MultiplierCount = 3
for i in word:
    if len(i) != 0:
        FinalList.append(i*MultiplierCount)
        MultiplierCount += 1
        if MultiplierCount > 5:
            MultiplierCount = 3
    else:
        FinalList.append(' ')

FinalOutput = "".join(FinalList)
print(FinalOutput)

It produces the following output.

hhheeeelllllppp mmmmeeeee

答案4

得分: 2

你可以在这里使用enumerate和模运算符:

word = ['h', 'e', 'l', 'p', 'm', 'e']
start = 3
end = 5
for i, a in enumerate(word):
    print(a * (i % (end - start + 1) + start), end='')

在你的原始代码中发生的情况是,你正在遍历整个单词3次,每次遍历都是为了范围3-6(不包括6)中的每个数字。在这段代码中,我们使用字符的索引对3(end-start+1)取模,然后加上3。因此,对于任何给定的数字,它将给我们一个结果为3、4或5。

编辑:

我想不出任何逻辑上合理的方式让你使用嵌套的for循环来解决这个问题,而不会变得非常复杂而没有原因。你要么最终会对range(3,6)中的每个字母进行迭代,要么像你已经在做的那样,对每个数字在range(3,6)中迭代一次你的单词中的每个字母。

英文:

You can make use of enumerate and modulus operators here:

word = ['h', 'e', 'l', 'p', 'm', 'e']
start = 3
end = 5
for i,a in enumerate(word):
    print(a * (i%(end-start+1)+start), end='')

What's happening in your original code is that you're iterating through the whole word 3 times, once for each number in the range 3-6 exclusive. In this code, we use the index of the character mod 3 (end-start+1), and then add 3. So for any given number, it will give us a result of 3, 4, or 5.

EDIT:

I can't think of any logical way for you to use a nested for-loop to solve this without getting really complicated for no reason. You'll either end up iterating over range(3,6) for each letter of your word, or, like you're already doing, iterating through each letter of your word once for each number in range(3,6).

huangapple
  • 本文由 发表于 2020年1月6日 21:51:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定