问题
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:
range()
also returns an iterable type, so there's no reason to convert it to alist
- It's bad practice to re-use (overwrite) the
list
keyword, and it doing so will lead to many more problems len_wl
doesn't serve a purpose yet- Because of #3, neither
wordlist
normessage
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