如何从不同的py文件返回项目列表

时间:2016-02-21 09:48:31

标签: python

我有2个.py文件(data.py,access.py)

access.py 中,我有几个字符串:

Japan = ['brown', 'cow', 'around']
Korea = ['black', 'chicken', '344']
China = ['grey', '3411', 'leaf']
Indonesia = ['red', 'green', '']

data.py 中,我有一个模块:

def whichcolour(country)
       print("access + country[1]")  # Doesn't work

我的结果

我想要实现的是,通过whichcolour运行data.py,它将返回/打印出该列表中的任何内容。

我知道print(access.Japan[1])有效..它返回cow

如何编写print语句以便它给出相同的结果?

1 个答案:

答案 0 :(得分:0)

使用字典。

access.py

countries = {
    'Japan': ['brown', 'cow', 'around'],
    'Korea': ['black', 'chicken', '344'],
    'China': ['grey', '3411', 'leaf'],
    'Indonesia': ['red', 'green', '']
}

data.py

from access import countries

def whichcolour(country, countries):
    print('{} has the color {}'.format(country, countries[country][0]))

for country in countries:
    whichcolour(country, countries)

输出:

Japan has the color brown
Korea has the color black
China has the color grey
Indonesia has the color red

我不是100%肯定你想做什么(印度尼西亚有两种颜色),但这应该让你开始。