Python:使用整数扩展变量字符串 [英] Python: Expanding a string of variables with integers

查看:172
本文介绍了Python:使用整数扩展变量字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是Python新手,在编程中学习更基本的东西。
现在我正在尝试创建一个函数来复制一组数字不同的名字。

I'm still new to Python and learning the more basic things in programming. Right now i'm trying to create a function that will dupilicate a set of numbers varies names.

示例:

def expand('d3f4e2')
>dddffffee

我不知道如何为此编写函数。
基本上我理解你想把字母变量加到旁边的数字变量上。

I'm not sure how to write the function for this. Basically i understand you want to times the letter variable to the number variable beside it.

推荐答案

任何关键解决方案是将事物分成要重复的字符串对,然后重复计数,然后以锁定步骤迭代这些对。

The key to any solution is splitting things into pairs of strings to be repeated, and repeat counts, and then iterating those pairs in lock-step.

如果您只需要单字符串和单位数重复计数,这只是将字符串分成两个字符对,你可以用mshsayem的答案,或切片( s [:: 2] 是字符串, s [1 :: 2] 是计数。)

If you only need single-character strings and single-digit repeat counts, this is just breaking the string up into 2-character pairs, which you can do with mshsayem's answer, or with slicing (s[::2] is the strings, s[1::2] is the counts).

但如果你想要怎么做将其概括为多字母字符串和多位数?

But what if you want to generalize this to multi-letter strings and multi-digit counts?

好吧,不知何故,我们需要将字符串分组为数字和非数字的运行。如果我们能够做到这一点,我们可以使用完全相同的方式使用这些组,mshsayem的答案使用成对的字符。

Well, somehow we need to group the string into runs of digits and non-digits. If we could do that, we could use pairs of those groups in exactly the same way mshsayem's answer uses pairs of characters.

事实证明我们可以做到这一点容易。标准库中有一个很棒的函数叫做 groupby 允许您根据任何功能将任何内容分组到运行中。还有一个功能 isdigit 区分数字和非数字。

And it turns out that we can do this very easily. There's a nifty function in the standard library called groupby that lets you group anything into runs according to any function. And there's a function isdigit that distinguishes digits and non-digits.

因此,这可以获得我们想要的运行:

So, this gets us the runs we want:

>>> import itertools
>>> s = 'd13fx4e2'
>>> [''.join(group) for (key, group) in itertools.groupby(s, str.isdigit)]
['d', '13', 'ff', '4', 'e', '2']

现在我们将其压缩起来,就像mshsayem压缩字符一样:

Now we zip this up the same way that mshsayem zipped up the characters:

>>> groups = (''.join(group) for (key, group) in itertools.groupby(s, str.isdigit))
>>> ''.join(c*int(d) for (c, d) in zip(groups, groups))
'dddddddddddddfxfxfxfxee'

所以:

def expand(s):
    groups = (''.join(group) for (key, group) in itertools.groupby(s, str.isdigit))
    return ''.join(c*int(d) for (c, d) in zip(groups, groups))

这篇关于Python:使用整数扩展变量字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆