TypeError: 'set' object does not support indexing

牧云@^-^@ 提交于 2020-06-22 15:07:46

问题


I've just been doing some random stuff in Python 3.5. And with 15 minutes of spare time, I came up with this:

a = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
 "x", "y", "z"}
len_a = len(a)
list = list(range(0, len_a))
message = ""
wordlist = [ch for ch in message]
len_wl = len(wordlist)
for x in list:
    print (a[x])

But that satisfying feel of random success did not run over me. Instead, the feeling of failure did:

Traceback (most recent call last):
File "/Users/spathen/PycharmProjects/soapy/soup.py", line 9, in  <module>
print (a[x])
TypeError: 'set' object does not support indexing

Please help


回答1:


Try square brackets:

a = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
 "x", "y", "z"]

i.e.: use an list instead of a set




回答2:


As the error message says, set indeed does not support indexing, and a is a set, since you used set literals (braces) to specify its elements (available since Python 3.1). However, to extract elements from a set, you can simply iterate over them:

for i in a:
    print(i)



回答3:


@Sakib, your set a is already iterable. Please consider using this updated code instead of accessing elements by index.

a = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
for x in a:
  print ( x )

Additionally, your code doesn't show enough intent for us to help you get to your ultimate goal. Examples:

  1. range() also returns an iterable type, so there's no reason to convert it to a list
  2. It's bad practice to re-use (overwrite) the list keyword, and it doing so will lead to many more problems
  3. len_wl doesn't serve a purpose yet
  4. Because of #3, neither wordlist nor message have a purpose either

Hope this helps

PS - don't forget to select an answer




回答4:


try to modify your code like this.

a = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", 
      "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
      "x", "y", "z"}
list_a = list(a)
len_a = len(a)
list = list(range(0, len_a))
message = ""
wordlist = [ch for ch in message]
len_wl = len(wordlist)
for x in list:
   print list_a[x]

set doesn't support indexing however list support it, so here i convert set to list and get index of list.



来源:https://stackoverflow.com/questions/43991057/typeerror-set-object-does-not-support-indexing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!