将for循环中的值添加到数组中

时间:2018-08-20 14:05:11

标签: python python-3.x

我试图将状态数组的值的长度放入一个单独的数组中,然后按降序对其进行排序,但是我很难将字符串的所有长度值都放入该数组中,而没有一个迭代后的单个值。

states = ["Abia", "Adamawa", "Anambra", "Akwa Ibom", "Bauchi", "Bayelsa", "Benue", "Borno", "Cross River", "Delta", "Ebonyi", "Enugu", "Edo", "Ekiti", "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara", "Lagos", "Nasarawa", "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto", "Taraba", "Yobe", "Zamfara"]

for i in states:
    a = [len(i)]
    print(a)

4 个答案:

答案 0 :(得分:3)

由于您希望长度按降序排序,因此请使用sortedreverse=True并列出理解

states = ["Abia", "Adamawa", "Anambra", "Akwa Ibom", "Bauchi", "Bayelsa", "Benue", "Borno", "Cross River", "Delta", "Ebonyi", "Enugu", "Edo", "Ekiti", "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara", "Lagos", "Nasarawa", "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto", "Taraba", "Yobe", "Zamfara"]
a = sorted([len(i) for i in states], reverse=True)
print (a)

输出

[11, 9, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3]

要获得排序列表的索引而不使用NumPy数组,有很多方法:see here。我个人更喜欢直接使用NumPy的{​​{1}}。顾名思义,它以升序返回与排序后的数组/列表相对应的索引数组。要获得降序索引,您可以使用argsort来反转argsort返回的数组。以下是您的问题的解决方案:

[::-1]

输出

import numpy as np
states = ["Abia", "Adamawa", "Anambra", "Akwa Ibom", "Bauchi", "Bayelsa", "Benue", "Borno", "Cross River", "Delta", "Ebonyi", "Enugu", "Edo", "Ekiti", "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara", "Lagos", "Nasarawa", "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto", "Taraba", "Yobe", "Zamfara"]
a = [len(i) for i in states]
indices_sorted = np.argsort(a)[::-1] # [::-1] gives you indices for decreasing order

现在您可以看到,以上输出中的第一个索引是array([ 8, 3, 24, 35, 19, 1, 2, 30, 5, 4, 10, 16, 17, 33, 32, 31, 22, 13, 6, 7, 9, 11, 14, 25, 23, 20, 21, 26, 27, 34, 28, 18, 0, 12, 15, 29]) ,这意味着8的第9个元素是states。同样,您可以访问和验证其他元素。

答案 1 :(得分:2)

您可以使用列表理解:

lengths = [len(state) for state in states]

如果需要使用for循环,请创建一个列表并将其附加到该列表中:

lengths = []
for i in states:
    lengths.append(len(i))

答案 2 :(得分:1)

您也可以使用map函数来执行此操作,而无需使用for循环:

a = list(map(len,states))

答案 3 :(得分:0)

通过生成器:

async validate(payload: JwtPayload, done: ((err: any, value: any) => void)) {
    const user = await this.authService.validateUser(payload);
    if (!user) {
        return done(new UnauthorizedException(), false);
    }
    done(null, user);
}