I'm trying to create a simple 2D array of country names and capital cities. This was straightforward i Java, but I'm toiling in Python.
I'd like something along the lines of:
Scotland Edinburgh
England London
Wales Cardiff
Any thoughts?
例如,您可以创建两个数组,一个用于首都,一个用于国家,然后通过在同一索引中访问它们的值,您可以获得首都及其国家!
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']]
You would probably be better off using a dictionary though: How to use a Python dictionary?
I agree with luckydog32, the dictionary should be a good solution to this.
capitolDict = {'england':'london', 'whales': 'cardiff'}
print(capitolDict.get('england'))
First of all, make a list of country name and their respective capital city.
countries = ['ScotLand','England','Wales']
capitals = ['Edinburgh','London','Cardiff']
Then, You can zip countries and capitals into a single list of tuple. Here, tuple is immutable sequence.
sequence = zip(countries,capitals)
Now, display:
for country, capital in sequence:
print(country,capital)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.