邮政功能和列表理解

发布于 2025-02-08 19:02:33 字数 1455 浏览 2 评论 0原文

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

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

发布评论

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

评论(2

咆哮 2025-02-15 19:02:33

逐步说明:

i = input - 将函数存储在i中,以后称为

zip(i(),i(),i()) -如果用户输入10101101,这将返回[(1,1),(0,1),(1,1,0),(0,(0,(0,) 的两个字符串的元素是来自

1)] - in a a 和b zip(在示例中,它们首先设置为a = 1和b = 1,然后a = 0和b = 1等)

'01'[a!= b] < /code> - a!= b将返回布尔值 - 是的。 true = 1和false = 0,因此您可以将其用于索引。基本上,这说明如果A!= B:'1'如果a == b:'0'

'''。join - 最后,最后,将所有“ 0和1”一起加入一个字符串并打印

Explained step by step:

i=input - storing the function in i to be called later

zip(i(),i()) - if the user entered 1010 and 1101, this would return [(1, 1), (0, 1), (1, 0), (0, 1)] - the elements of both strings paired up

for a,b in - a and b are the pair from the zip (in the example they are first set to a=1 and b=1, then a=0 and b=1, etc.)

'01'[a!=b] - a!=b will return a boolean - either True or False. True = 1 and False = 0 so you can use this for indexing. Basically this says if a!=b: '1', if a==b: '0'

''.join - finally, join all the '0's and '1's together to make one string and print

挽袖吟 2025-02-15 19:02:33

如果您真的想将其制作为Oneliner,请删除分号并这样做:

print(''.join('01'[a!=b] for a, b in zip(input(), input())))
  1. Python会向用户询问两个输入字符串
  2. zip用元组创建一个值,所以“ HI”和“ HO”将成为[(h,h),(i,o)]
  3. 在列表理解中,您有一个字符串'01',可以用0或1索引,
  4. 这是您的expression [a!= b]确实,它评估true(1)或false(0),
  5. 因为您在所有元组上循环,所以输入中的每个字符都会发生这种情况字符串
  6. 最后,''。加入串联列表中的所有元素,然后将其打印

If you really want to make it a oneliner, remove the semicolon and do it like this:

print(''.join('01'[a!=b] for a, b in zip(input(), input())))
  1. Python will ask the user for two input strings
  2. zip creates an iterable with tuples, so "hi" and "ho" will become [(h,h), (i,o)]
  3. in the list comprehension, you've got a string '01' that can be indexed with either 0 or 1
  4. that is what your expression [a!=b] does, it evaluates to either True (1) or False (0)
  5. because you loop over all tuples, this happens for every character in your input strings
  6. finally, ''.join concatenates all elements in your list, and this gets printed
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文