我有这个
list = ['John', 21, 'Smith', 30, 'James', 25]
我想将它们分为以下
name = ['John', 'Smith', 'James']
age = [21, 30, 25]
答案 0 :(得分:2)
您可以执行此操作。请勿使用keywords
和built-in
作为变量名。
使用切片
Understanding Slicing Notation
lst=['John', 21, 'Smith', 30, 'James', 25]
name=lst[::2]
age=lst[1::2]
或者您可以使用 列表理解
name=[val for idx,val in enumerate(lst) if idx%2==0]
age=[val for idx,val in enumerate(lst) if idx%2==1]
答案 1 :(得分:1)
遍历列表。如果可以将元素的索引除以2而没有余数,则将元素添加到列表名称。如果将索引除以2时还有余数,则将元素追加到列表年龄。列表索引从0开始。枚举使元素的索引在迭代列表时可用。用除法运算符检查除数的余数。
lst = ['John', 21, 'Smith', 30, 'James', 25]
#Create list name to store the names
name = []
#Create list age to store the age
age = []
# use for loop to access every element of lst
# using enumerate(lst) let's us access the index of every element in the variable index see reference [0]
# The indexes of the list elements are as following:
# John: 0, 21: 1, Smith: 2, 30: 3, James: 4, 25: 5
for index,element in enumerate(lst):
#Check if the index of an element can be divided by 2 without a remainder
#This is true for the elements John, Smith and James:
#0 / 2 = 0 remainder 0
#2 / 2 = 1 remainder 0
#4 / 2 = 2 remainder 0
if index % 2 == 0:
name.append(element)
# If the division of the index of an element yields remainder, add the element to the list age
# This is true for the elements 21, 30 and 25:
# 1 / 2 = 0 remainder 1
# 3 / 2 = 1 remainder 1
# 5 / 2 = 2 remainder 1
else:
age.append(element)
print(name)
print(age)
参考:
[0] https://docs.python.org/3/library/functions.html#enumerate
[1] https://docs.python.org/3.3/reference/expressions.html#binary-arithmetic-operations。
答案 2 :(得分:0)
一种不太方便的方法是使用列表索引:
<Router>
<Switch>
<Route exact path="/series" component={SeriesLibrary} />
<Route exact path="/series/:series_id" component={EpisodeLibrary} />
<Route
path="/series/:series_id/episode/:episode_id"
component={Episode}
/>
</Switch>
</Router>