【问题标题】:How to create a list with perticular strings from another list in python using for loop?python - 如何使用for循环从python中的另一个列表中创建具有特定字符串的列表?
【发布时间】:2021-04-15 05:46:34
【问题描述】:

我有一个列表类“state_wise_data”。

列表是

[
array(['Andaman and Nicobar Islands', 5201, 5050, 62, 89,'12-04-2021 22.58'], dtype=object), array(['Andhra Pradesh', 928664, 898238, 7311, 23115, '12-04-2021 20.49'], dtype=object), 
....
]

我从中提取了第一个值。

for value in state_wise_data:
     print(value[0])

输出

Andaman and Nicobar Islands
Andhra Pradesh
.
.

现在我想以这种特殊格式创建一个列表

form.country.choices = [('Andaman and Nicobar Islands', 'Andaman and Nicobar Islands'), (' Andhra Pradesh', ' Andhra Pradesh'),.....('n', 'n')]

我尝试了列表理解......

例如:

res = [(n, n) for n in map(str, range(1,10))]

这将产生

[('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ..., ('10', '10')]

同样,我可以得到

[('Andaman and Nicobar Islands', 'Andaman and Nicobar Islands'), (' Andhra Pradesh', ' Andhra Pradesh'),.....('n', 'n')]

请帮忙? ????

【问题讨论】:

  • 您的数据组织不当。如果这是单个 2D numpy 数组,则可以使用切片表示法。但作为一个简单的 numpy 对象列表,您必须使用 [(n[0],n[0]) for n in state_wise_data]。

标签: python python-3.x list for-loop nested-lists


【解决方案1】:

它就像 ABC 一样简单。

lists = [('nothing','your'),('everything','their'),('something','our')]

[(item[0],item[0]) for item in lists]

为了让它更快,您可以使用 numpy 并立即对 numpy 数组进行切片

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-07
    • 2017-04-17
    • 2022-01-09
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2021-02-25
    相关资源
    最近更新 更多