简体   繁体   English

在 Python 的列表迭代中确保有序?

[英]Is ordered ensured in list iteration in Python?

Let's suppose to have a list of strings, named strings , in Python and to execute this line:假设在 Python 中有一个名为strings的字符串列表并执行此行:

lengths = [ len(value) for value in strings ]

Is the strings list order kept? strings列表顺序是否保留? I mean, can I be sure that lengths[i] corresponds to strings[i] ?我的意思是,我可以确定lengths[i]对应于strings[i]吗? I've tryed many times and it works but I'm not sure if my experiments were special cases or the rule.我已经尝试了很多次并且它有效,但我不确定我的实验是特殊情况还是规则。

Thanks in advance提前致谢

For lists, yes.对于列表,是的。 That is one of the fundamental properties of lists: that they're ordered.这是列表的基本属性之一:它们是有序的。

It should be noted though that what you're doing though is known as "parallel arrays" (having several "arrays" to maintain a linked state), and is often considered to be poor practice.应该注意的是,尽管您正在做的事情被称为“并行数组”(具有多个“数组”来保持链接状态),但通常被认为是不好的做法。 If you change one list, you must change the other in the same way, or they'll be out of sync, and then you have real problems.如果您更改一个列表,则必须以相同的方式更改另一个列表,否则它们将不同步,然后您就会遇到真正的问题。

A dictionary would likely be the better option here:字典可能是这里更好的选择:

lengths_dict = {value:len(value) for value in strings}
print(lengths_dict["some_word"])  # Prints its length

Or maybe if you want lookups by index, a list of tuples:或者如果你想按索引查找,一个元组列表:

lengths = [(value, len(value)) for value in strings]
word, length = lengths[1]

Yes, since list in python are sequences you can be sure that each length that you have in the list of the length is corresponding to the string length in the same index.是的,由于 python 中的列表是序列,因此您可以确定长度列表中的每个长度都对应于同一索引中的字符串长度。 like the following code represents像下面的代码代表

a = ['a', 'ab', 'abc', 'abcd'] 
print([len(i) for i in a])

Output Output

[1, 2, 3, 4]

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

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