简体   繁体   English

使用循环比较两个列表以查找匹配值

[英]Using loops to compare two lists to find matching values

I have two lists, pPop and sPop. 我有两个列表,pPop和sPop。 sPop is pPop after being sorted in ascending numerical order (they're populations of towns/cities). sPop是按升序排序的pPop(它们是城镇/城市的人口)。

I also have four other lists, pName, pType, pLat, and pLong, but I'm not really doing anything with them at this point in time. 我还拥有其他四个列表,即pName,pType,pLat和pLong,但目前我还没有对它们做任何事情。

I need to sort this list of cities by ascending population size, and I basically have been told to do it using what I know currently - which isn't that much. 我需要按人口数量的升序对城市列表进行排序,并且基本上已被告知要使用我目前所知的方法来进行排序,这还不算什么。 I've tried this using tuples and other stuff, but those fall under things I haven't been taught. 我已经尝试过使用元组和其他东西,但是那些都属于我没有教过的东西。

I have to compare sPop to pPop and use the information I get from that to reorder the other four lists, so I can spit them out in a .csv file. 我必须将sPop与pPop进行比较,并使用从中获得的信息对其他四个列表进行重新排序,以便将它们吐出到.csv文件中。

I get the idea, I'm just not sure of the execution. 我知道了,只是不确定执行情况。 I think I need to run a loop over all of sPop, with a loop inside that running for all pPop, which checks if sPop[x] = pPop[y], (x from 0 to len(sPop)) giving some kind of affirmative response when it's true. 我需要对所有sPop运行一个循环,在其中为所有pPop运行一个循环,该循环检查sPop [x] = pPop [y],(从0到len(sPop)的x)是否提供某种肯定的回答,当它是真的。 If it's true, then set pVar[y] equal to sVar[x]. 如果为true,则将pVar [y]设置为等于sVar [x]。

After writing this out it seems fine, I'm just not entirely sure how to loop for every index in python. 在写完之后看起来还不错,我只是不完全确定如何为python中的每个索引循环。 When I do, say, 当我说时

for x in sPop

it's 它的

x = sPop[i] i=range(0:len(sPop))

when I'd prefer x to refer to the index itself, not the value of the array/list at that index. 当我希望x引用索引本身,而不是该索引处的数组/列表的值时。

Short version : loop over indices in an array with 简短版本 :循环遍历数组中的索引

for x in array 用于数组中的x

where x refers to the index. 其中x表示索引。 How do? 怎么办 If you can't, best way to refer to the index within a loop? 如果不能,那么在循环中引用索引的最佳方法是? It's late and my brain is fried on this problem after spending about six hours trying to work this out a few days ago using different methods. 已经很晚了,几天前我花了六个小时尝试使用不同的方法来解决这个问题,但我的大脑对此问题感到不知所措。

EDIT: 编辑:

Alright, got it. 好,知道了 For anyone who is somehow curious (maybe someone'll stumble across this one in five years), you loop over sPop, then over pPop, (use for indexX, varX in enumerate(list) twice) then use 对于任何好奇的人(也许有人会在五年内偶然发现),您可以遍历sPop,然后遍历pPop(用于indexX,两次枚举(列表)中的varX),然后使用

if varX ==varY
sortedList.append(initialList[varY])

Can't put down the actual code or I'd probably get smacked with a plagiarism checker. 无法放下实际代码,否则我可能会被窃检查器打晕。

To get the index: 获取索引:

for index, x in enumerate(sPop):
    print index, x
for x in range(len(sPop)):
    item = sPop[x]

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

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