简体   繁体   English

应用算术运算符在python中列出元素

[英]Applying arithmetic operators to list elements in python

string="hi how are you"
s =string.split()
print(s)
for i in range(len(s)):
    print(s[i])
    s += s[i]
print(s)

I just began learning python and I noticed something weird which didn't make sense to me.我刚开始学习 python,我注意到一些奇怪的东西,这对我来说没有意义。

So when I do s += s[i] shouldn't I be getting something like this ['hi', 'how', 'are', 'you', 'hi', 'how', 'are', 'you']所以当我做s += s[i]时我不应该得到这样的东西['hi', 'how', 'are', 'you', 'hi', 'how', 'are', 'you']

but instead I'm getting something like this: ['hi', 'how', 'are', 'you', 'h', 'i', 'h', 'o', 'w', 'a', 'r', 'e', 'y', 'o', 'u'] .但相反,我得到了这样的东西: ['hi', 'how', 'are', 'you', 'h', 'i', 'h', 'o', 'w', 'a', 'r', 'e', 'y', 'o', 'u']

why do the individual letters get added?为什么要添加单个字母?

I know we can obtain this ['hi', 'how', 'are', 'you', 'hi', 'how', 'are', 'you'] using the append function but isn't + supposed to do the same thing ?我知道我们可以使用 append 函数获得这个['hi', 'how', 'are', 'you', 'hi', 'how', 'are', 'you']但不是+应该做同样的事 ?

The += operator for lists doesn't append an element to a list, it concatenates two lists.列表的+=运算符不会将元素附加到列表,而是连接两个列表。 for example:例如:

a = [1, 2, 3]
b = [2, 3, 4]
>>> a += b # will give you [1, 2, 3, 2, 3, 4]

Now, if we try to use + operator for appending an element it will throw an exception现在,如果我们尝试使用+运算符来附加元素,它将抛出异常

>>> a += 2
TypeError: 'int' object is not iterable

Now let's come to your case.现在让我们来看看你的情况。 The string is interpreted as a list of characters, that's why the operation you try to do is viewed as concatenating a list with a list of chars.该字符串被解释为字符列表,这就是为什么您尝试执行的操作被视为将列表与字符列表连接起来的原因。

>>> a = [] 
>>> a += "hello"
>>> a

['h', 'e', 'l', 'l', 'o']

Actually no, the actual output is fine, this is why.实际上没有,实际输出很好,这就是为什么。

when you try to add "hi" to ['hi', 'how', 'are', 'you'], you are trying to add a string to a list of strings.当您尝试将“hi”添加到 ['hi', 'how', 'are', 'you'] 时,您是在尝试将字符串添加到字符串列表中。 This should be an error.这应该是一个错误。 But actually strings are already a list of characters.但实际上字符串已经是一个字符列表。 What you are doing is that you are effectively adding lists to lists, hence ['hi', 'how', 'are', 'you'] get combined with each letter in "Hi"您正在做的是有效地将列表添加到列表中,因此 ['hi', 'how', 'are', 'you'] 与“Hi”中的每个字母组合在一起

What you want to do can either be achieved by s.append(s[i]) or by s += [s[i]]您想要做的可以通过s.append(s[i])或通过s += [s[i]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM