我有一个清单
L = Counter(mywords)
Run Code Online (Sandbox Code Playgroud)
在哪里
mywords = ['Well', 'Jim', 'opportunity', 'I', 'Governor', 'University', 'Denver', 'hospitality', 'There', 'lot', 'points', 'I', 'make', 'tonight', 'important', '20', 'years', 'ago', 'I', 'luckiest', 'man', 'earth', 'Michelle', 'agreed', 'marry', '(Laughter)', 'And', 'I', 'Sweetie', 'happy']
Run Code Online (Sandbox Code Playgroud)
它比那要长得多,但这是一个片段。
现在我接下来要做的是:
print ("\n".join(c.most_common(10)))
Run Code Online (Sandbox Code Playgroud)
因为我希望它显示该列表中 10 个最常用的单词及其计数,但我希望它为列表中的每个项目打印出新行,而不是我收到此错误:
TypeError: sequence item 0: expected str instance, tuple found
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,使用 Python 3。
可能重复:
Python列表理解与 地图
什么时候应该使用map/filter而不是list comprehension或generator表达式?
我必须将值列表更改为多个数组,如下所示:
list_train_data = [u'Class 1',
u'Class 2',
u'Class 3',
u'Class 4',
u'Class 5']
Run Code Online (Sandbox Code Playgroud)
我需要将这个值放入一个数组中:
train_set = [['Class 1'],['Class 2'],['Class 3'],['Class 4'],['Class 5']]
Run Code Online (Sandbox Code Playgroud)
如果可能的话不要用于循环.
我想知道是否有更Pythonic的方法可以执行以下操作,也许使用字典理解:
A = some list
D = {}
for i,v in enumerate(A):
if v in D:
D[v].append(i)
else:
D[v] = [i]
Run Code Online (Sandbox Code Playgroud) python list-comprehension python-3.x dictionary-comprehension
我有一个数字,有两种值列表1或0与具有长度1024我想找到的次数是两个给定的名单上重叠的所有索引(但只有当他们匹配值== 1),但可以"似乎想到了保持比较次数低的方法.目前我的方法是获取我的列表的所有索引值== 1,并得到两个列表的交集,例如
#for each list, do the following
for x,j in enumerate(list1):
if j == 1:
idx_list.append(x)
# compare two lists
num_overlap = set(idx_list1).intersection(idx_list2)
Run Code Online (Sandbox Code Playgroud)
这是找到这个值的最有效方法吗?
例如输入/输出(仅显示6个值而不是1024个):
list1 = [1 0 1 0 0 0]
list2 = [1 0 0 0 0 0]
num_overlap = 1 (both lists have ```1``` at index 0)
Run Code Online (Sandbox Code Playgroud) 我有以下场景。
import pandas as pd
d = {'col1': [1, 2, 3], 'col2': [['apple'], [], ['romaine', 'potatoes']}
df = pd.DataFrame(data=d)
Run Code Online (Sandbox Code Playgroud)
所以数据框是:
col1 col2
0 1 [apple]
1 2 []
2 3 [romaine, potatoes]
Run Code Online (Sandbox Code Playgroud)
我还有一本字典:
my_dict = {"apple" : "fruit", "potatoes" : "vegetable", "romaine" : "lettuce"}
Run Code Online (Sandbox Code Playgroud)
我想创建另一列“col3”,它将包含上面 my_dict 中的值列表:
col1 col2 col3
0 1 [apple] [fruit]
1 2 [] []
2 3 [romaine, potatoes] [lettuce, vegetable]
Run Code Online (Sandbox Code Playgroud)
我想使用apply、map、lambda编写一行代码来实现这一点:
df["col3"] = df.col2.apply(map(lambda x: pass if not x else condition_dict[x]))
Run Code Online (Sandbox Code Playgroud)
我真的被困住了,想知道是否有可能不编写单独的函数然后作为参数传递来应用。
我有一个列表和一个字典,我想用字典的值替换列表项.我的问题的简化版本如下:
#This is a list
a=['dog', 'cat', 'cow']
#This is a dictionary
b={'dog': 'barks', 'cat': 'meows', 'cow': 'moos' }
Run Code Online (Sandbox Code Playgroud)
现在列出一个[0]即狗在字典b中被搜索并且将找到关键狗并且我希望它的价值咆哮代替列表中的狗a.
预期的输出应该是这样的
a=['barks','meows','moos']
Run Code Online (Sandbox Code Playgroud)
我已经能够在三个文本文件的帮助下做到这一点,其中一个文本文件的格式为'key-value',另外两个我借助split()函数分别提取了键和值,然后再匹配索引位置以获得所需的结果.但是,问题是代码太长了.我尝试做上面提到的方法,但无法取代值.
我可以用什么其他方法代替'lambda'
def calculate_fees(self):
return sum(map(lambda x: x.fee, self.bookings.values()))
def calculate_donations(self):
return sum(map(lambda x: x.donation, self.bookings.values()))
def __str__(self):
output = 'Event: {0} {1} {2}\n'.format(self.event_id, self.event_date, self.venue) + \
'Miles: {0}\n'.format(self.miles) + \
'Max Places: {0}\n'.format(self.max_places) + \
'Basic Fee: £{0}'.format(self.basic_fee)
if self.bookings:
output += '\nRunners:\n' + \
'\n'.join(map(lambda x: '{0} {1}'.format(x.runner_id, x.club_id), self.bookings.values()))
return output
Run Code Online (Sandbox Code Playgroud) 请注意,我是 python 新手:我正在尝试创建一个已定义的函数,可以将列表转换为字符串,并允许我放入分隔符。分隔符必须是“,”。我当前的思维过程是将列表中的每个项目添加到一个空字符串变量中,然后尝试使用 range 函数添加分隔符。我只想使用 str() 和 range( )。
def list2Str(lisConv, sep = ', '):
var = ''
for i in lisConv:
var = var + str(i)
#test line
print(var, "test line")
var1 = int(var)
for a in range(var1):
print(str(var1)[a], sep = ', ')
list1 = [2,0,1,6]
result = list2Str(list1, ', ')
print(result)
Run Code Online (Sandbox Code Playgroud) python ×10
dictionary ×3
list ×3
lambda ×2
data-science ×1
function ×1
interpreter ×1
numpy ×1
pandas ×1
performance ×1
python-3.x ×1
string ×1
tuples ×1