Найти - Пользователи
Полная версия: Двумерный массив в python
Начало » Python для новичков » Двумерный массив в python
1
Vady
Вопрос такой: как создать двумерный массив, если изначально не знаю сколько элементов в каждом измерении массива?
Пример: есть группа Group, есть студенты Students.
arr={}
Group = 1
arr[Group] = {}
Students = 1
arr[Group][Students] = u'Иванов'
Group = 1
arr[Group] = {}
Students = 2
arr[Group][Students] = u'Петров'
Group = 1
arr[Group] = {}
Students = 3
arr[Group][Students] = u'Сидоров'
for stud in arr[1]:
    print(arr[1][stud])
На выходе вместо всех перечисленных фамилий получаю только последнего студента “Сидоров”.
Shaman
arr={}
Group = 1
arr[Group] = {}
Students = 1
arr[Group][Students] = u'Иванов'
Group = 1
#arr[Group] = {}
Students = 2
arr[Group][Students] = u'Петров'
Group = 1
#arr[Group] = {}
Students = 3
arr[Group][Students] = u'Сидоров'
for stud in arr[1]:
    print(arr[1][stud])
или
arr={}
Group = 1
arr[Group] = {}
Students = 1
arr[Group][Students] = u'Иванов'
Group = 2
arr[Group] = {}
Students = 2
arr[Group][Students] = u'Петров'
Group = 3
arr[Group] = {}
Students = 3
arr[Group][Students] = u'Сидоров'
for stud in arr[1]:
    print(arr[1][stud])
FishHook
Не очень понятно, чего вы хотите сделать, но обычно для подобных конструкций используют defaultdict

#!/usr/bin/env python
# -* coding: utf-8 -*-
from collections import defaultdict
d = defaultdict(list)
d["Students"].append(u"Иванов")
d["Students"].append(u"Петров")
d["Groups"].append(u"НТ-981")
d["Groups"].append(u"НТ-982")
print d
Vady

Спасибо большое всем за ответы!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB