【问题标题】:Arrays not sorting properly in python数组在python中没有正确排序
【发布时间】:2015-03-12 01:20:52
【问题描述】:

当我尝试在 python 中使用 sorted() 函数时,它只会按字母顺序对每个数组中的元素进行排序,因为前 3 个输出是:

[u'A', u'a', u'a', u'f', u'g', u'h', u'i', u'n', u'n', u's', u't']
[u'N', u'a', u'e', u'g', u'i', u'i', u'r']
[u'C', u'a', u'e', u'm', u'n', u'o', u'o', u'r']

这些应该分别是阿富汗、尼日利亚和喀麦隆,但它们只在自己的数组中排序。

我的代码哪里出错了?

import urllib2
import csv
from bs4 import BeautifulSoup

url = "http://en.wikipedia.org/wiki/List_of_ongoing_armed_conflicts"
soup = BeautifulSoup(urllib2.urlopen(url))

#f= csv.writer(open("test.csv","w"))
#f.writerow(["location"])
def unique(countries):
    seen = set()
    for country in countries:
        l = country.lower()
        if l in seen:
            continue
        seen.add(l)
        yield country



for row in soup.select('table.wikitable tr'):
    cells = row.find_all('td')
    if cells:
        for location in cells[3].find_all(text=True):
            location = location.split()

            for locations in unique(location):
                print sorted(locations)

#f.writerow([location])

【问题讨论】:

    标签: python arrays sorting


    【解决方案1】:

    通过循环的每次迭代,您可以获得一个或多个位置(作为列表)。所有这些都需要添加到一个列表中才能对其进行排序。

    我们使用extend 方法来做到这一点。

    locs = []  # contains all locations
    for row in soup.select('table.wikitable tr'):
        cells = row.find_all('td')
        if cells:
            # location here returns a list
            for location in cells[3].find_all(text=True):
                locs.extend(location.split())
    
    print sorted(locs)
    

    sorted(locs) 也将是一个列表。要打印特定元素,您可以这样做

    specific_element = sorted(locs)[index]
    

    【讨论】:

    • 感谢这正是我所需要的!然后我将如何选择完全迭代的字符串?我试图只打印特定元素但无济于事,因为 print sorted(locs[any number]) 说它超出范围
    • 我已经更新了我的答案。 sorted 需要一个列表,但 locs[index] 会给你一个元素。要从排序列表中取出元素,您必须执行sorted(locs)[index]。
    • 因此,当我这样做时,我会得到很多 [ ] 值,然后过了一会儿它会出现第一个名称,然后是所有名称,我将如何选择最后一个可迭代对象?
    • 获取最后排序的位置? sorted(locs)[-1]。负索引选择从列表末尾开始的元素。
    【解决方案2】:

    你的变量名很糟糕,让你感到困惑。 location 是位置列表,locations 是单个位置!

    你想要的:

    for locations in cells[3].find_all(text=True):
        locations = locations.split()
    
        for location in sorted(unique(locations)):
            print location 
    

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多