字典操作... 索引 / 迭代 / 验证
我想要做以下几件事:
- 检查位置 i 的键/值
- 检查这个键/值是否包含某个字符串
- 删除这个键/值,或者把它存到另一个变量里
这段代码在 Java 中的写法是:
//Some list...
ArrayList<String> example;
...
//Index into data structure
example.get(i);
//Check for some string...
if (example.get(i).contains("someText")){
somestuff;
}
//Store in some other variable
exam = example.get(i)
我在 Java 中就是想这样做,不过我想用 Python 的字典来实现这个功能,但我不太确定这样是否可行,因为我觉得 Python 的文档看起来有点难懂。
4 个回答
1
你可以这样做,来实现和你在Java示例中一样的效果。
# Some list
example = {} # or example = dict()
...
# Index into data estructure.
example[example.keys(i)]
# Check for some string...
if example[example.keys(i)] == 'someText' :
pass
# Store in some other variable...
exam = example[example.keys(i)]
del example[example.keys(i)]
# ...or
exam = example.pop(example.keys(i))
3
直接翻译(对于一个 ArrayList<String>
,你不想要一个字典,你想要一个列表):
example = ["foo", "bar", "baz"]
str = example[i]
if "someText" in str:
somestuff()
不过,先熟悉一下 for
这个关键词吧,它在 Python 中非常好用:
for str in example:
if "someText" in str:
someStuff()
这里有一个使用字典的例子:
fruits = {
"apple": "red",
"orange": "orange",
"banana": "yellow",
"pear": "green"
}
for key in fruits:
if fruits[key] == "apple":
print "An apple is my favorite fruit, and it is", fruits[key]
else:
print "A", key, "is not my favorite fruit, and it is", fruits[key]
在字典上用 for
循环时,你得到的是键,具体的值你还得自己去找。正如 Alex 指出的那样,我们在信息这么少的情况下回答你,可能有点偏离主题,而且听起来你对数据结构的理解还不够深入(字典每次迭代时可能会得到不同的顺序)。
5
Python中的字典是用哈希表来实现的,所以它没有固定的顺序。因此,提到“位置i”这个概念在字典里是完全没有意义的——就像问哪个字典条目最黄色,或者哪个条目最不像骆驼……这些概念根本不适用于字典的条目,而“位置i”也是一样完全不适用。
那么这个i
到底是从哪里来的呢,也就是说,你真正想解决的问题是什么?如果你只是想遍历字典,可以直接这样做,不需要用“数字索引”这种方式。如果你需要保持某种特定的顺序,那就不要用字典,而是用其他的数据结构。如果你能具体说明一下你想解决的目的,我相信我们可以帮助你。