创建一个二维字符串数组
Create a 2D String Array
我正在尝试创建一个简单的国家/地区名称和首都城市的二维数组。这在我 Java 中很简单,但我在 Python 中很辛苦。
我想要以下内容:
Scotland Edinburgh
England London
Wales Cardiff
有什么想法吗?
例如,您可以制作两个数组,一个用于首都,一个用于国家,然后通过在同一索引处访问它们的值,您可以获得首都及其国家!
capitalCities= ["Edinburgh", "London", "Cardiff"]
countries= ["Scotland", "England", "Wales"]
>>> arr = [['england', 'london'], ['whales', 'cardiff']]
>>> arr
[['england', 'london'], ['whales', 'cardiff']]
>>> arr[1][0]
'whales'
>>> arr.append(['scottland', 'Edinburgh'])
>>> arr
[['england', 'london'], ['whales', 'cardiff'], ['scottland', 'Edinburgh']]
虽然你最好还是使用字典:How to use a Python dictionary?
同意luckydog32的观点,字典应该可以很好的解决这个问题
capitolDict = {'england':'london', 'whales': 'cardiff'}
print(capitolDict.get('england'))
首先,列出国家名称及其各自的首都。
countries = ['ScotLand','England','Wales']
capitals = ['Edinburgh','London','Cardiff']
然后,您可以将国家和首都压缩到一个元组列表中。这里,元组是不可变序列。
sequence = zip(countries,capitals)
现在,显示:
for country, capital in sequence:
print(country,capital)
我正在尝试创建一个简单的国家/地区名称和首都城市的二维数组。这在我 Java 中很简单,但我在 Python 中很辛苦。
我想要以下内容:
Scotland Edinburgh
England London
Wales Cardiff
有什么想法吗?
例如,您可以制作两个数组,一个用于首都,一个用于国家,然后通过在同一索引处访问它们的值,您可以获得首都及其国家!
capitalCities= ["Edinburgh", "London", "Cardiff"]
countries= ["Scotland", "England", "Wales"]
>>> arr = [['england', 'london'], ['whales', 'cardiff']]
>>> arr
[['england', 'london'], ['whales', 'cardiff']]
>>> arr[1][0]
'whales'
>>> arr.append(['scottland', 'Edinburgh'])
>>> arr
[['england', 'london'], ['whales', 'cardiff'], ['scottland', 'Edinburgh']]
虽然你最好还是使用字典:How to use a Python dictionary?
同意luckydog32的观点,字典应该可以很好的解决这个问题
capitolDict = {'england':'london', 'whales': 'cardiff'}
print(capitolDict.get('england'))
首先,列出国家名称及其各自的首都。
countries = ['ScotLand','England','Wales']
capitals = ['Edinburgh','London','Cardiff']
然后,您可以将国家和首都压缩到一个元组列表中。这里,元组是不可变序列。
sequence = zip(countries,capitals)
现在,显示:
for country, capital in sequence:
print(country,capital)