我如何拆分和映射输入,例如' s1,10'对于两个变量,一个str和另一个整数

发布于 2025-02-07 18:44:59 字数 238 浏览 3 评论 0原文

我正在阅读输入“ S1,10”。第一个组件是字符串,第二个是整数。他们被逗号分开。

我尝试过x = input()。split(',')。这将创建一个列表['S1','10']。如何创建一个列表['s1',10],其中第二个元素是整数?

我已经在两个步骤的过程中解决了这一点。 bp = input()。split(',') bp [1] = int(bp [1])

可以单一步骤完成吗?我们如何使用不同的数据类型分开?

I am reading an input 'S1,10'. First component is a string and second is an integer. They are separated by comma.

I have tried x = input().split(','). This creates a list ['S1','10']. How can I create a list ['S1', 10] where the second element is an integer?

I have solved this in a two step process.
bp = input().split(',')
bp[1] = int(bp[1])

Can it be done in a single step? How can we split with different datatypes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尹雨沫 2025-02-14 18:44:59

我的意思是,如果您真的想强迫它,它可以单行完成,

x = [s if i == 0 else int(s) for i,s in enumerate(input().split(','))]

但归根结底,代码是供人类理解的。如果我是你,我会保留你拥有的东西。

I mean, if you really want to force it, it can be done in a single line

x = [s if i == 0 else int(s) for i,s in enumerate(input().split(','))]

But at the end of the day, code is for humans to understand. If I were you I would keep what you have.

夜唯美灬不弃 2025-02-14 18:44:59

这是使用 zip()函数的解决方案。通过这种方法,很容易变化哪些功能适用于拆分字符串的部分。

x = [f(s) for f, s in zip([str, int], input().split(','))]

Here is a solution using the zip() function. With this approach it is easy to vary which functions to apply to the parts of the split string.

x = [f(s) for f, s in zip([str, int], input().split(','))]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文